<template>
  <div class="app-container">
    <!-- <el-button type="primary" @click="queryPatient" >会员查询</el-button> -->
    <!-- <br> -->
    <!-- <div style="width: 100px;height: 100px;border: 1px solid red;"></div> -->
      <el-tabs v-model="editableTabsValue" type="border-card" @tab-remove="removeTab" style="padding: 30px 0;">
      <el-tab-pane
        label="诊中列表"
        name="诊中列表"
      >
        <el-collapse >
          <el-collapse-item title="岗位状态" name="jobStatus">
            <div class="job-status">
              <div class="job-status-item" v-for="item in jobStatusList">
                <span>{{item.workAddressName}} {{ item.jobOfficeName }}</span><br>
                <span>出诊医生：{{item.doctorName}}</span><br>
                <span>诊前：{{ item.pendingCount }}人</span><br>
                <span>诊中：{{ item.visitingCount }}人</span><br>
                <span>诊后：{{ item.doneCount }}人</span><br>
                <span>完成：{{ item.doneCount }}人</span><br>
              </div>
              
            </div>
          </el-collapse-item>
        </el-collapse>
        <br>
        <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        :row-class-name="tableRowClassName"
      > 
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="会员编号" width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.patientCode }}
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.patientName }}
          </template>
        </el-table-column>
        <el-table-column label="等级" width="80" align="center">
          <template slot-scope="scope">
            {{ scope.row.vipLevel }}
          </template>
        </el-table-column>
        <el-table-column label="就诊方式" width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.typeName }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="就诊医生" width="150" align="center">
          <template slot-scope="scope">
            {{ scope.row.doctorName }}
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="就诊科室" width="150" align="center">
          <template slot-scope="scope">
            {{ scope.row.jobOfficeName }}
          </template>
        </el-table-column>
        <el-table-column label="就诊诊室" width="150" align="center">
          <template slot-scope="scope">
            {{ scope.row.workAddressName }}
          </template>
        </el-table-column> -->
        <el-table-column label="就诊类型" width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.visitType }}
          </template>
        </el-table-column>
        <el-table-column label="挂号后时长" width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.afterGuidanceTime }}
          </template>
        </el-table-column>
        <el-table-column label="就诊排队时长" width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.remainderTime }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="挂号费(元)" width="150" align="center">
          <template slot-scope="scope">
            {{ scope.row.registerPrice }}
          </template>
        </el-table-column> -->
        <el-table-column label="诊前实验室检查" width="150" align="center">
          <template slot-scope="scope">
            {{ scope.row.remainderTime }}
          </template>
        </el-table-column>
        <el-table-column label="就诊状态" width="150" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusColorFilter">{{ scope.row.status | statusFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="操作" align="center" width="400" >
          <template slot-scope="scope">
            <el-button type="primary" @click="optionVisit(scope.row)">诊中操作</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="->, total, prev, pager, next"
        :total="this.total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="clickCurPage"
        >
      </el-pagination>
      </el-tab-pane>
      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
        :closable="item.isClose == true"
      >
        <!-- get patient list -->
        <div v-if="editableTabsValue == '会员查询'">
          <div class="header">
            <div style="display: flex;flex-direction: column;justify-content: end;width: 60%;">
              <el-form :model="query" ref="query" label-width="80px">
                <el-row :gutter=10>
                  <el-col :span=16>
                    <el-form-item label-width="250px" label="姓名/编号/电话(后四位)/身份证号" prop="name" >
                        <el-input v-model="query.name" placeholder="请输入姓名/编号/电话(后四位)/身份证号"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span=8>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-search" @click="search" >搜索</el-button>
                      <el-button @click="resetForm('query')">重置</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>

            <!-- <el-card class="box-card" v-for="report in reports" :key="report.jobOfficeId"  >
              <div slot="header" class="clearfix">
                <span>{{ report.jobOfficeName }}</span>
              </div>
              <div class="text item">
                {{'候诊人数: ' + report.waitingCount }}
              </div>
              <div class="text item">
                {{'就诊人数: ' + report.doingCount }}
              </div>
            </el-card> -->
          </div>
          <el-table
            v-loading="patientListLoading"
            :data="patientList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
          > 
            <el-table-column align="center" label="序号" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="编号" width="120" align="center">
              <template slot-scope="scope">
                {{ scope.row.code }}
              </template>
            </el-table-column>
            <el-table-column label="姓名" width="120" align="center">
              <template slot-scope="scope">
                {{ scope.row.name }}
              </template>
            </el-table-column>
            <el-table-column label="手机号" width="120" align="center">
              <template slot-scope="scope">
                {{ scope.row.phone }}
              </template>
            </el-table-column>
            <el-table-column label="身份证号" width="160" align="center">
              <template slot-scope="scope">
                {{ scope.row.idCard }}
              </template>
            </el-table-column>
            <el-table-column label="性别" width="80" align="center">
              <template slot-scope="scope">
                {{ scope.row.sex }}
              </template>
            </el-table-column>
            <el-table-column label="出生年月" width="130" align="center">
              <template slot-scope="scope">
                {{ scope.row.birthday + ' ' }} {{ scope.row.birthdayType | birthdayTypeFilter }} 
              </template>
            </el-table-column>
            <el-table-column label="年龄" width="80" align="center">
              <template slot-scope="scope">
                {{ scope.row.age }}
              </template>
            </el-table-column>
            <el-table-column label="入籍时长" width="150" align="center">
              <template slot-scope="scope">
                {{ scope.row.joinDuration }}
              </template>
            </el-table-column>
            <el-table-column label="就诊状态" width="150" align="center">
              <template slot-scope="scope">
                {{ scope.row.visitStatus }}
              </template>
            </el-table-column>
            <el-table-column label="会员等级" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.vipLevel?scope.row.vipLevel:'V0' }}
              </template>
            </el-table-column>
            <el-table-column label="就诊日期" width="130" align="center">
              <template slot-scope="scope">
                {{ scope.row.visitDate }}
              </template>
            </el-table-column>
            <el-table-column class-name="status-col" :label="'信息查询\n信息修改\n等级设置'" align="center" width="300" >
              <template slot-scope="scope">
                <el-button type="primary" @click="optionPatient(scope.row)">操作</el-button>
                <!-- <el-dropdown size="medium" trigger="click" @command="optionPatient" >
                  <el-button type="primary">
                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="composeValue(scope.row, 1)" >基础信息查询</el-dropdown-item>
                    <el-dropdown-item :command="composeValue(scope.row, 2)" >基础信息修改</el-dropdown-item>
                    <el-dropdown-item :command="composeValue(scope.row, 3)" >会员等级设置</el-dropdown-item>
                    <el-dropdown-item :command="composeValue(scope.row, 4)" divided >会员就诊记录查询</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown> -->
                <!-- <el-button type="warning"  @click="toGuidance(scope.row)" size="small">挂号</el-button>
                <el-button type="primary"  @click="getInfo(scope.row)" size="small">详情</el-button>
                <el-button type="success"  @click="update(scope.row)" size="small">修改</el-button>
                <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            layout="->, total, prev, pager, next"
            :total="total"
            :current-page="currentPage"
            :page-size="pageSize"
            @current-change="clickCurPage"
            >
          </el-pagination>
        </div>


        <!-- patient detail -->
        <div v-else>
          <el-container>
            <el-main>
              <div class="patient-base-info" style="font-size: 16px;top: 84px;height: 100px;line-height: 105px;"> 就诊状态: 今日无就诊</div>
              <div class="patient-base-info" >
                <el-collapse >
                  <el-collapse-item name="1">
                    <template slot="title">
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title"> 基础信息: </span>
                          <span class="main-head-title">
                            {{item.content.code + ' '}}
                            {{item.content.name + ' '}}
                            {{item.content.sex + ' '}}
                            {{item.content.age + '周岁 /'}}
                            {{'手机尾号:'+ item.content.phone + ' /'}}
                            {{'身份证号:'+ item.content.idCard + ' /'}}
                            {{'出生日期:'+ item.content.birthday + ' '}}{{item.content.birthdayType | birthdayTypeFilter}}{{' /'}}
                            {{'会员等级:'}}{{item.content.vipLevel?item.content.vipLevel:'V0' }}
                          </span>
                        </el-col>
                      </el-row>
                    </template>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">就诊信息: </span>
                          <span class="main-head-title">
                            就诊信息内容
                          </span>
                          </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">卡券信息: </span>
                          <span class="main-head-title">卡券信息内容 </span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">用药信息: </span>
                          <span class="main-head-title">用药信息内容 </span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">预案信息: </span>
                          <span class="main-head-title">预案信息内容</span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">诊断信息: </span>
                          <span class="main-head-title">诊断信息内容</span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">就诊习惯: </span>
                          <span class="main-head-title">就诊习惯内容</span>
                        </el-col>
                      </el-row>
                  </el-collapse-item>
                </el-collapse>

              </div>
              

              <el-tabs v-model="item.content.patientTabsValue" type="border-card" closable @tab-remove="(targetName) => removePatientTab(targetName, item.content)">
                <el-tab-pane
                  v-for="patientTab in item.content.patientTabs"
                  :key="patientTab.name"
                  :label="patientTab.title"
                  :name="patientTab.name"
                >
                <div v-if="item.content.patientTabsValue == '会员管理'">
                  <el-form :model="item.content" label-width="120px" :rules="addPatientFormRules">
                    <el-row :gutter="10">
                      <!-- <el-col :span=8 >
                        <el-form-item label="编号">
                          <el-input v-model="addPatientForm.code" />
                        </el-form-item>
                      </el-col> -->
                      <el-col :span=8 >
                        <el-form-item label="姓名" prop="name">
                          <el-input v-model="item.content.name" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="性别" prop="sex">
                          <el-select v-model="item.content.sex" placeholder="请选择" :disabled="true" >
                            <el-option
                              v-for="item in sexEnum"
                              :key="item"
                              :label="item"
                              :value="item">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=6 >
                        <el-form-item label="手机号1" prop="phone">
                          <el-input v-model="item.content.phone" @input="inputPhone" maxlength="11" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="手机号2" >
                          <el-input v-model="item.content.phoneTwo" @input="inputPhone" maxlength="11" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="手机号3" >
                          <el-input v-model="item.content.phoneThree" @input="inputPhone" maxlength="11" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="身份证号" prop="idCard">
                          <el-input style="width: 100%" v-model="item.content.idCard" @input="inputIdCard" maxlength="18" :disabled="true" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=4 >
                        <el-form-item label="出生日期" prop="birthday">
                          <el-date-picker v-model="item.content.birthday" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" @change="changeBirthday" :disabled="true" ></el-date-picker>
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 :offset=4>
                        <el-form-item label="农历/公历" prop="birthdayType">
                          <el-select v-model="item.content.birthdayType" placeholder="请选择" :disabled="true" >
                            <el-option
                              v-for="item in birthdayTypeEnum"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="年龄">
                          <el-input v-model="item.content.age" type="Number" min=0  :disabled="true" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=8 >
                        <el-form-item label="来源" prop="source">
                          <el-select v-model="item.content.source" placeholder="请选择" :disabled="true" >
                            <el-option
                              v-for="item in sourceEnum"
                              :key="item.id"
                              :label="item.source"
                              :value="item.id"
                              >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span=8 >
                        <el-form-item label="介绍人" v-if="item.content.source == 1 || item.content.source == 2" >
                          <el-select v-if="item.content.source == 1" v-model="item.content.introducer" placeholder="请选择" :disabled="true">
                            <el-option
                              v-for="item in patientEnum"
                              :key="item.id"
                              :label="item.code + ' - ' +item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                          <el-select v-else-if="item.content.source == 2" v-model="item.content.introducer" placeholder="请选择" :disabled="true">
                            <el-option
                              v-for="item in userEnum"
                              :key="item.id"
                              :label="item.jobNumber + ' - ' + item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
                      <div v-for="(address, index) in item.content.addressList" :key="index" >
                        <el-row :gutter="10" v-if="index != 0">
                          <el-col :span=6>
                            <el-form-item label="多址说明" prop="multiAddressDes">
                              <el-select v-model="address.multiAddressDes" placeholder="请选择" :disabled="true" >
                                <el-option
                                  v-for="item in multiAddressDesEnum"
                                  :key="item"
                                  :label="item"
                                  :value="item"
                                >
                                </el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span=6>
                            <el-form-item label="说明填写" v-if="address.isOtherAddress == 1" prop="multiAddressDesOther">
                              <el-input v-model="address.multiAddressDesOther" :disabled="true"/>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="10">
                          <el-col :span=8 >
                            <el-form-item label="省/市/区" prop="addressPre" >
                              <el-cascader
                                :disabled="true"
                                size="large"
                                :options="options"
                                v-model="address.addressPre"
                                :props="{ value: 'label', label: 'label'}"
                                >
                              </el-cascader>
                            </el-form-item>
                          </el-col>
                          <el-col :span=6>
                            <el-form-item label="小区" prop="addressMid">
                              <el-input v-model="address.addressMid" :disabled="true" ></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span=10 >
                            <el-form-item label="详细地址" prop="addressInfo">
                              <el-input v-model="address.addressInfo" :disabled="true" ></el-input>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="10">
                          <el-col :span=8 >
                            <el-form-item label="距离" prop="retailStore">
                              <el-select v-model="address.retailStore" placeholder="门店请选择" :disabled="true" >
                                <el-option
                                  v-for="item in deptEnum"
                                  :key="item"
                                  :label="item"
                                  :value="item"
                                >
                                </el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span=8 >j
                            <el-form-item label="公交站数" prop="distance">
                              <el-input v-model="address.distance" type="Number" min=0 :disabled="true" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-divider></el-divider>
                      </div>
                    </div>
                  </el-form>
                </div>

                <div v-if="item.content.patientTabsValue == '会员就诊记录查询'">
                  会员就诊记录查询内容
                </div>
                
                <div v-if="item.content.patientTabsValue == '诊中处置'">
                  <el-container>
                    <!-- <el-aside width="70%">
                      <div style="width: 100%;text-align: left;">
                        <span class="main-head-title">诊中·诊室检查开立 / </span>
                        <span class="main-head-title">诊中·实验室检查开立 / </span>
                        <span class="main-head-title">诊中·信息采集 / </span>
                        <br>
                        <span class="main-head-title">诊中·诊断开具 / </span>
                        <span class="main-head-title">诊中·处方开具 / </span>
                        <span class="main-head-title">诊中·预案填写</span>
                      </div>
                    </el-aside> -->
                    <!-- <el-main> -->
                      <div style="width: 100%;height: 100%;text-align: left;padding: 5px;">
                        <el-button  type="primary" :disabled="item.content.status == 5 || item.content.status == 6">停止服务</el-button>
                      </div>
                    <!-- </el-main> -->
                  </el-container>
                  <el-collapse v-model="item.content.visitActiveName" >
                    <!-- <el-collapse-item title="诊中·诊室检查开立" name="诊中·诊室检查开立">
                      <div>诊室检查开立内容</div>
                      <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                        <el-button type="primary" @click="confirmVisit(item.content, 1)">诊室检查提交</el-button>
                      </div>
                    </el-collapse-item> -->
                    <el-collapse-item name="诊中·实验室检查开立">
                      <template #title>
                        <span style="font-size: 20px;font-weight: 600">诊中·实验室检查开立</span>
                      </template>
                      <div>
                        <el-form >
                          <el-row :gutter="10">
                            <el-col :span=12 >
                              <el-form-item label="储值卡" >
                                <el-select size="mini" style="width: 160px;" v-model="item.content.visitInspectionCard"   placeholder="请选择" >
                                  <el-option
                                    @click.native="selectVisitInspectionCard(item.content)"
                                    v-for="cardItem in item.content.cardList"
                                    :key="cardItem.id"
                                    :label="cardItem.name"
                                    :value="cardItem.id">
                                  </el-option>
                                </el-select>
                              </el-form-item>
                            </el-col>
                          </el-row>
                        </el-form>
                        <div class="body-item-contents">
                          <!-- <span style="dispaly: inline-block;margin: 5px;">分装商品总价: {{ form.subPackagePlanTotalAmount }}</span> -->
                          
                          <el-table
                            style="width: 100%;white-space: pre-wrap;"
                            :data="item.content.visitInspectionList"
                            element-loading-text="Loading"
                            :row-class-name="drugIsPaidClassName"
                            border
                            fit
                            :header-cell-style="{ height: '5px', padding: '0 0' }"
                            :cell-style="{padding: '8px 0', height: '78px'}"
                          > 
                            <el-table-column label="序号" align="center" width="50">
                              <template slot-scope="subDrugScope">
                                <div>{{ subDrugScope.$index+1 }}</div>
                                <el-button class="del-btn"  type="danger" icon="el-icon-delete" circle @click="delDrug(subDrugScope.$index, item.content.visitInspectionList, item.content)" :disabled="subDrugScope.row.status != 0"></el-button> 
                              </template>
                            </el-table-column>
                            <el-table-column :label="'实验室检测商品名称'" align="center" width="240">
                              <template slot-scope="subDrugScope">
                                <span>{{ subDrugScope.row.code + '[' +subDrugScope.row.commonName + ']'}}</span><br>
                                <span>{{ subDrugScope.row.name }}</span><br>
                                <span>{{ subDrugScope.row.specs }}</span>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'单价'" align="center" width="75" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.unitPrice + '/' + subDrugScope.row.outerUnit }}
                              </template>
                            </el-table-column>
                            <el-table-column :label="'储值卡\n单价'" align="center" width="75">
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.unitPrice + '/' + subDrugScope.row.outerUnit }}
                              </template>
                            </el-table-column>
                            <el-table-column label="处方/药房操作" align="center" >
                              <el-table-column label="数量" align="center" width="130">
                                <template slot-scope="subDrugScope">
                                  <el-input size= "mini" style="width: 90px" type="Number" min=0 placeholder="请输入" v-model="subDrugScope.row.realQuantity" @input="inputRealQuantity(item.content)" :disabled="subDrugScope.row.status != 0">
                                    <template slot="append">
                                      <span style="font-size: 14px">{{ subDrugScope.row.outerUnit }}</span>
                                    </template>
                                  </el-input>
                                </template>
                              </el-table-column>
                              <el-table-column :label="'单品金额'" align="center" width="80">
                                <template slot-scope="subDrugScope">
                                  {{ subDrugScope.row.unitPrice }}
                                </template>
                              </el-table-column>
                              <el-table-column :label="'储值卡金额'" align="center" width="90">
                                <template slot-scope="subDrugScope">
                                  {{ subDrugScope.row.totalPrice1 }}
                                </template>
                              </el-table-column>
                              <el-table-column :label="'操作'" align="center" width="120">
                                <template slot-scope="subDrugScope">
                                  <el-radio-group :value="subDrugScope.row.operation" style="display: flex;flex-direction: column;text-align: left;" @input="(value) => selectoperation(value, subDrugScope.row)" :disabled="subDrugScope.row.status != 0">
                                    <el-radio :label="1" >选择操作</el-radio>
                                    <el-radio :label="2" >不选择操作</el-radio>
                                    <el-radio :label="3" >缴费预存</el-radio>
                                  </el-radio-group><br>
                                  <div v-if="subDrugScope.row.operation == 2 && subDrugScope.row.operationMark" ><span style="font-size: 12px;color: red;">不操作原因:{{ subDrugScope.row.operationMark }}</span></div>
                                </template>
                              </el-table-column>
                              <el-table-column label="使用节点" align="center" width="80">
                                <template slot-scope="subDrugScope">
                                  <el-radio-group v-model="subDrugScope.row.operationStep" style="display: flex;flex-direction: column;text-align: left;" :disabled="subDrugScope.row.status != 0">
                                    <el-radio :label="1">诊中</el-radio>
                                    <el-radio :label="2">诊后</el-radio>
                                  </el-radio-group>
                                </template>
                              </el-table-column>
                              <el-table-column label="来源" align="center" width="60">
                                <template slot-scope="subDrugScope">
                                  {{ subDrugScope.row.source }}
                                  <!-- <el-input type="textarea" v-model="subDrugScope.row.source" ></el-input> -->
                                </template>
                              </el-table-column>
                            </el-table-column>
                            <el-table-column :label="'结果查\n询时长'" align="center" width="60" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.resultTime == '小时' ? subDrugScope.row.timeNumber + '小时' : subDrugScope.row.resultTime }}
                              </template>
                            </el-table-column>
                            <el-table-column label="上次检查时间" align="center" width="80">
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.lastTime }}
                              </template>
                            </el-table-column>
                            <el-table-column label="活动" align="center" width="200">

                            </el-table-column>
                            
                          </el-table>
                          <el-autocomplete
                            value-key="pinyinCode"
                            class="inline-input"
                            v-model="item.content.inspectionSearchValue"
                            :fetch-suggestions="(queryString, cb) => queryDrugSearch(queryString, cb, item.content, 2)"
                            placeholder="请输入 实验室检查 拼音简码"
                            :trigger-on-focus="false"
                            @select="(check) => {handleDrugSelect(check, 2, item.content)}"
                            style="width: 100%;"
                          >
                            <template slot-scope="{ item }">
                              <span >{{ item.name? item.name+'/' : '' }}</span>
                              <span >{{ item.commonName? item.commonName+' ' : '' }}</span>
                              <span >{{ item.form? item.form+' ' : '' }}</span>
                              <span >{{ item.specs? item.specs+' ' : ''  }}</span>
                              <span >{{ item.factory? item.factory+' ' : '' }}</span>
                              <span >{{ item.productTime ? '(' + item.productTime.split('T')[0] + '—' + item.expiration.split('T')[0] + ')' : '' }}</span>
                            </template>
                          </el-autocomplete>
                          <el-divider content-position="left">按处方/药房取药计算</el-divider>
                          <el-table
                            style="width: 100%;white-space: pre-wrap;"
                            :data="item.content.visitInspectionRealReport"
                            element-loading-text="Loading"
                            border
                            fit
                            :header-cell-style="{ height: '5px', padding: '0 0' }"
                          > 
                            <el-table-column label="处方金额" align="center" width="80">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.planAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="储值卡处方金额" align="center" width="120">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.cardPlanAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="活动处方金额" align="center" width="120">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.activityPlanAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'活动+储值卡金额'" align="center" width="140">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.activityCardPlanAmount }} <br>
                              </template>
                            </el-table-column>
                          </el-table>
                        </div>
                      </div>
                      <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                        <el-button type="primary" @click="confirmVisit(item.content, 2)" :disabled="item.content.status == 5 || item.content.status == 6">实验室检查提交</el-button>
                      </div>
                    </el-collapse-item>
                    <!-- <el-collapse-item title="诊中·信息采集" name="诊中·信息采集">
                      <div>信息采集内容</div>
                      <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                        <el-button type="primary" @click="confirmVisit(item.content, 3)">信息采集提交</el-button>
                      </div>
                    </el-collapse-item> -->
                    <!-- <el-collapse-item title="诊中·诊断开具" name="诊中·诊断开具">
                      <div>
                        诊断开具内容
                      </div>
                      <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                        <el-button type="primary" @click="confirmVisit(item.content, 4)">诊断提交</el-button>
                      </div>
                    </el-collapse-item> -->
                    <el-collapse-item  name="诊中·处方开具">
                      <template #title>
                        <span style="font-size: 20px;font-weight: 600">诊中·处方开具</span>
                      </template>
                      
                      <el-divider content-position="center"><span style="font-size: 18px;font-weight: 600">处方开具·分装商品</span></el-divider>

                      <div>
                        <!-- <span>上次结束服药日期？ 断药？天</span> -->
                        <el-descriptions class="margin-top" :column="2" size="large">
                          <el-descriptions-item label="开始发药日期">
                            <el-date-picker 
                              :picker-options="pickerOptions"
                              size="mini" 
                              v-model="item.content.visit.startUsageTime" 
                              type="date" 
                              placeholder="选择日期" 
                              @input="inputStartTime(item.content)" 
                            ></el-date-picker>
                          </el-descriptions-item>
                          <el-descriptions-item label="服药结束日期">
                            <el-date-picker size="mini" v-model="item.content.visit.endUsageTime" type="date" placeholder="选择日期" :disabled="true"></el-date-picker>
                          </el-descriptions-item>
                        </el-descriptions>
                        <!-- <div class="body-item-title" ><span>分装商品</span></div> -->
                        <div class="body-item-contents">
                          <!-- <span style="dispaly: inline-block;margin: 5px;">分装商品总价: {{ form.subPackagePlanTotalAmount }}</span> -->
                          
                          <el-table
                            style="width: 100%;white-space: pre-wrap;"
                            :data="item.content.visitSubPackageDrugList"
                            element-loading-text="Loading"
                            :header-cell-style="{ height: '5px', padding: '0 0' }"
                            :row-class-name="drugIsPaidClassName"
                            border
                            fit
                            :cell-style="{padding: '8px 0', height: '78px'}"
                          > 
                            <el-table-column label="序号" align="center" width="50">
                              <template slot-scope="subDrugScope">
                                <div>{{ subDrugScope.row.serialNum }}</div>
                                <el-button style="padding: 5px 0" v-if="subDrugScope.row.usagePurpose == '日常' && !(''+subDrugScope.row.serialNum).includes('.')" type="text" size="mini" @click="addGroup(subDrugScope.$index, item.content)" :disabled="subDrugScope.row.status != 0" >建组</el-button>
                                <el-button class="del-btn"  type="danger" icon="el-icon-delete" circle @click="delDrug(subDrugScope.$index, item.content.visitSubPackageDrugList, item.content)" :disabled="subDrugScope.row.status != 0" ></el-button>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'分装商品名称'" align="center" width="240">
                              <template slot-scope="subDrugScope">
                                <span>{{ subDrugScope.row.code != '' ? subDrugScope.row.code + '[' +subDrugScope.row.commonName + ']' : ''}}</span><br>
                                <span>{{ subDrugScope.row.name }}</span><br>
                                <span>{{ subDrugScope.row.specs }}</span>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'单价\n(元/片)'" align="center" width="70" >
                              <template slot-scope="subDrugScope">
                                <div class="second-row" >
                                  <div>{{ subDrugScope.row.unitPrice }}</div>
                                </div>
                              </template>
                            </el-table-column>
                            <el-table-column label="处方" align="center" >
                              <el-table-column :label="'处方天数'" align="center" width="120" >
                                <template #header >
                                  <span>处方天数</span><br>
                                  <el-input size="mini" style="width: 70px;" type="Number" min=0 placeholder="请输入" v-model="item.content.visit.planUsageDays" @input="inputPatientPlanUsageDays(item.content)" @blur="blurPatientPlanUsageDays(item.content)" :disabled="item.content.visitSubPackageDrugList != 0 && item.content.visitSubPackageDrugList[0].status != 0"></el-input>
                                </template>
                                <template slot-scope="subDrugScope">
                                  <el-input :class="subDrugScope.row.usagePurpose == '日常特' ? 'first-row' : 'second-row'" size="mini" style="width: 100px;" type="Number" min=0 placeholder="请输入" v-model="subDrugScope.row.planUsageDays" @input="inputSubDrugPlanUsageDays(subDrugScope.$index, item.content)" @blur="blurSubDrugPlanUsageDays(subDrugScope.$index, item.content)" :disabled="subDrugScope.row.isDisabledPlanUsageDays || subDrugScope.row.status != 0">
                                    <template slot="append">
                                      <span style="font-size: 14px;">{{ '天 ' }}</span>
                                    </template>
                                  </el-input>
                                  <br>
                                  <!-- 日常特 -->
                                  <el-input class="second-row" style="width: 114px;" size="mini" v-if="subDrugScope.row.usagePurpose == '日常特'" type="Number" min=1 v-model="subDrugScope.row.planUsageStartDays" @input="inputSubDrugPlanUsageStartDays(subDrugScope.row, item.content)" :disabled="subDrugScope.row.status != 0">
                                    <template slot="append">
                                      <span style="font-size: 14px;">{{ '天起' }}</span>
                                    </template>
                                  </el-input>
                                  <br>
                                  <div class="third-row"  style="font-size: 14px;">{{ subDrugScope.row.planUsageDaysInfo }}</div>
                                  <!-- 补 -->
                                  <div class="first-row repair-box" v-if="subDrugScope.row.usagePurpose == '补'">
                                    <el-date-picker 
                                      style="width: 25px;"
                                      size="mini"
                                      v-model="subDrugScope.row.repairDate" 
                                      type="daterange" 
                                      range-separator="" 
                                      start-placeholder=""
                                      end-placeholder="" 
                                      format=" "
                                      @input="changeRepairDate(subDrugScope.row)"
                                      :disabled="subDrugScope.row.status != 0">
                                    </el-date-picker>
                                  </div>
                                  <span class="third-row" style="left: 3px;" v-if="subDrugScope.row.usagePurpose == '补'" >{{ subDrugScope.row.repairDateStr }}</span>
                                </template>
                              </el-table-column>
                              <el-table-column label="片/次" align="center"  width="80">
                                <template slot-scope="subDrugScope">
                                  <el-select class="second-row" style="width: 70px;" size="mini" v-model="subDrugScope.row.eachUsageAmount" placeholder="请选择"  :disabled="subDrugScope.row.status != 0" >
                                    <el-option
                                      v-for="eachUsageAmount in meteredEnum"
                                      :key="eachUsageAmount"
                                      :label="eachUsageAmount"
                                      :value="eachUsageAmount"
                                      @click.native="selectEachUsageAmount(eachUsageAmount, subDrugScope.row, item.content)"
                                      >
                                    </el-option>
                                  </el-select>
                                </template>
                              </el-table-column>
                              <el-table-column label="次/天" align="center" width="90">
                                <template slot-scope="subDrugScope">
                                  <el-select class="second-row" style="width: 80px;" size="mini" v-model="subDrugScope.row.usageMode" placeholder="请选择"  :disabled="subDrugScope.row.status != 0" >
                                    <el-option
                                      v-for="item in usageModeEnum"
                                      :key="item"
                                      :label="item"
                                      :value="item">
                                    </el-option>
                                  </el-select>
                                </template>
                              </el-table-column>
                              <el-table-column label="用途" align="center" width="95">
                                <template slot-scope="subDrugScope">
                                    <el-select class="second-row" size="mini" v-model="subDrugScope.row.usagePurpose" placeholder="请选择" :disabled="subDrugScope.row.isGroup || (''+subDrugScope.row.serialNum).includes('.') || subDrugScope.row.status != 0" >
                                      <el-option
                                        v-for="usagePurpose in usagePurposeEnum"
                                        :key="usagePurpose"
                                        :label="usagePurpose"
                                        :value="usagePurpose"
                                        @click.native="selectUsagePurpose(usagePurpose, subDrugScope.row, item.content)"
                                        >
                                      </el-option>
                                    </el-select>
                                </template>
                              </el-table-column>
                              <el-table-column :label="'处方\n片数'" align="center" width="60">
                                <template slot-scope="subDrugScope">
                                  <div class="second-row" >{{ subDrugScope.row.planQuantity? subDrugScope.row.planQuantity : '' }}</div>
                                </template>
                              </el-table-column>
                              <el-table-column :label="'处方单\n品金额'" align="center" width="65">
                                <template slot-scope="subDrugScope">
                                  <div class="second-row" >
                                    {{ subDrugScope.row.planSalePrice }}
                                  </div>
                                </template>
                              </el-table-column>

                            </el-table-column>
                            <el-table-column label="药房取药" align="center" width="100" >
                              <el-table-column :label="'取药天数'" align="center" width="50" >
                                <template slot-scope="subDrugScope">
                                  <div class="second-row" >
                                    {{ subDrugScope.row.realUsageDays }}
                                  </div>
                                </template>
                              </el-table-column>
                              <el-table-column label="取药片数" align="center" width="100">
                                <template slot-scope="subDrugScope">
                                  <div class="second-row" >
                                    <div style="display: flex;justify-content: center;">
                                      <span style="display: inline-block;" >{{ subDrugScope.row.realQuantity ? subDrugScope.row.realQuantity : 0 }} </span>
                                      <el-checkbox style="margin-left: 5px;display: inline-block;" v-model="subDrugScope.row.isReserve" @change="changeReserve(subDrugScope.row, item.content)" :disabled="!subDrugScope.row.planQuantity || subDrugScope.row.status != 0" >剩余</el-checkbox>
                                    </div>
                                    <el-input size="mini"  v-if="subDrugScope.row.isReserve" v-model="subDrugScope.row.reserveNum" type="Number" min=0 @input="inputReserveNum(subDrugScope.row, item.content)">
                                      <span slot="append">{{ subDrugScope.row.innerUnit }}</span>
                                    </el-input>
                                  </div>
                                </template>
                              </el-table-column>
                              <el-table-column :label="'取药单\n品金额'" align="center" width="65">
                                <template slot-scope="subDrugScope">
                                  <div class="second-row" >
                                    {{ subDrugScope.row.realSalePrice }}
                                  </div>
                                </template>
                              </el-table-column>

                            </el-table-column>
                            
                          </el-table>
                          <el-autocomplete
                            value-key="pinyinCode"
                            class="inline-input"
                            v-model="item.content.subPackageDrugSearchValue"
                            :fetch-suggestions="(queryString, cb) => queryDrugSearch(queryString, cb, item.content, 51)"
                            placeholder="请输入 分装药品 拼音简码"
                            :trigger-on-focus="true"
                            @select="(subDrug) => {handleDrugSelect(subDrug, 51, item.content)}"
                            style="width: 100%;"
                          >
                            <template slot-scope="{ item }">
                              <span >{{ item.code? item.code : '' }}</span>
                              <span >{{ item.commonName? '['+item.commonName+'] ' : '' }}</span>
                              <span >{{ item.name? item.name+' ' : '' }}</span>
                              <span >{{ item.specs? item.specs+' ' : ''  }}</span>
                              <span >{{ item.form? item.form+' ' : '' }}</span>
                              <span >{{ item.num? '库存:[' +item.num+'] ' : '库存:[0]' }}</span>
                              <!-- <span >{{ item.factory? item.factory+' ' : '' }}</span> -->
                              <span >{{ item.productTime ? '(' + item.productTime.split('T')[0] + '—' + item.expiration.split('T')[0] + ')' : '' }}</span>
                            </template>
                          </el-autocomplete>
                          <el-form class="" report-submit="false" bindsubmit="" bindreset="">
                            <el-form-item label="药房提醒">
                                <el-input type="textarea" v-model="item.content.visit.drugMark"></el-input>
                            </el-form-item>
                          </el-form>
                          <el-divider content-position="left">按处方计算</el-divider>
                          <el-table
                            style="width: 100%;white-space: pre-wrap;"
                            :data="item.content.visitSubPackageDrugPlanReport"
                            element-loading-text="Loading"
                            border
                            fit
                            :header-cell-style="{ height: '5px', padding: '0 0' }"
                          > 
                            <el-table-column label="处方" align="center" width="50">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.title }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'天数'" align="center" width="50">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.planUsageDays }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'金额'" align="center" width="70">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.planAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'日均\n金额'" align="center" width="60">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.planAmountInDay }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'储值卡\n金额'" align="center" width="60">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.planAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'储值卡\n日均金额'" align="center" width="75">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.planAmountInDay }} <br>
                              </template>
                            </el-table-column>
                            <!-- <el-table-column :label="'按28天处方\n计算金额'" align="center" width="120">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.planAmountInMonth }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'按28天处方\n储值卡计算金额'" align="center" width="120">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.planAmountInMonth }} <br>
                              </template>
                            </el-table-column> -->
                            <el-table-column  align="center" width="130">
                              <template #header >
                                <span>按 </span>
                                <el-input style="width: 90px;margin-top: 2px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.planReportsDay" @input="inputPatientPlanUsageDays(item.content)">
                                  <template slot="append">
                                    天
                                  </template>
                                </el-input>
                                <div>{{'\n金额计算'}}</div>
                              </template>
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.planAmountInplanReportsDay }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column  align="center" width="130">
                              <template #header >
                                <div>{{ '按 ' }}{{ item.content.planReportsDay?item.content.planReportsDay:'--' }} {{ '天' }}</div>
                                <div>{{'\n储值卡金额计算'}}</div>
                              </template>
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.planAmountInplanReportsDay }} <br>
                              </template>
                            </el-table-column>
                          </el-table>
                          <el-divider content-position="left">按药房取药计算</el-divider>
                          <el-table
                            style="width: 100%;white-space: pre-wrap;"
                            :data="item.content.visitSubPackageDrugRealReport"
                            element-loading-text="Loading"
                            border
                            fit
                            :header-cell-style="{ height: '5px', padding: '0 0' }"
                          > 
                            <el-table-column label="取药" align="center" width="50">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.title }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="天数" align="center" width="50">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realUsageDays }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="金额" align="center" width="70">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'日均\n金额'" align="center" width="60">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realAmountInDay }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'储值卡\n金额'" align="center" width="60">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'储值卡\n日均金额'" align="center" width="75">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realAmountInDay }} <br>
                              </template>
                            </el-table-column>
                            <!-- <el-table-column :label="'按28天取药\n计算金额'" align="center" width="120">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realAmountInMonth }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'按28天取药\n储值卡计算金额'" align="center" width="120">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realAmountInMonth }} <br>
                              </template>
                            </el-table-column> -->
                            <el-table-column  align="center" width="130">
                              <template #header >
                                <span>按 </span>
                                <el-input style="width: 90px;margin-top: 2px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.realReportsDay" @input="inputPatientPlanUsageDays(item.content)">
                                  <template slot="append">
                                    天
                                  </template>
                                </el-input>
                                <div>取药金额计算</div>
                              </template>
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realAmountInRealReportsDay }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column  align="center" width="130">
                              <template #header >
                                <div>{{ '按 ' }}{{ item.content.realReportsDay?item.content.realReportsDay:'--' }} {{ '天' }}</div>
                                <div>{{'\n储值卡金额计算'}}</div>
                              </template>
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realAmountInRealReportsDay }} <br>
                              </template>
                            </el-table-column>
                          </el-table>
                        </div>
                      </div>
                      <el-divider></el-divider>
                      <el-divider></el-divider>
                      <el-divider content-position="center"><span style="font-size: 18px;font-weight: 600">处方开具·整装商品</span></el-divider>
                      
                      <div>
                        <!-- <span>上次整装开具日期 ?</span> -->
                        <!-- <div class="body-item-title" ><span>整装商品</span></div> -->
                        <div class="body-item-contents">
                          <!-- <span style="dispaly: inline-block;margin: 5px;">分装商品总价: {{ form.subPackagePlanTotalAmount }}</span> -->
                          <el-form >
                            <el-row :gutter="10">
                              <el-col :span=12 >
                                <el-form-item label="储值卡">
                                  <el-select size="mini" style="width: 160px;" v-model="item.content.visitPackageCard" placeholder="请选择" >
                                    <el-option
                                      v-for="item in item.content.cardList"
                                      :key="item.id"
                                      :label="item.name"
                                      :value="item.id">
                                    </el-option>
                                  </el-select>
                                </el-form-item>
                              </el-col>
                            </el-row>
                          </el-form>
                          <el-table
                            style="width: 100%;white-space: pre-wrap;"
                            :data="item.content.visitPackageDrugList"
                            element-loading-text="Loading"
                            :row-class-name="drugIsPaidClassName"
                            border
                            fit
                            :header-cell-style="{ height: '5px', padding: '0 0' }"
                            :cell-style="{padding: '10px 0', height: '80px'}"
                          > 
                            <el-table-column label="序号" align="center" width="50">
                              <template slot-scope="subDrugScope">
                                <div> {{ subDrugScope.$index+1 }}</div>
                                <el-button class="del-btn"  type="danger" icon="el-icon-delete" circle @click="delDrug(subDrugScope.$index, item.content.visitPackageDrugList, item.content)" :disabled="subDrugScope.row.status != 0"></el-button>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'整装商品名称'" align="center" width="240">
                              <template slot-scope="subDrugScope">
                                <span>{{ subDrugScope.row.code + '[' +subDrugScope.row.commonName + ']'}}</span><br>
                                <span>{{ subDrugScope.row.name }}</span><br>
                                <span>{{ subDrugScope.row.specs }}</span>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'单价'" align="center" width="60" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.unitPrice + '/' + subDrugScope.row.specs.substring(subDrugScope.row.specs.length -1) }}
                              </template>
                            </el-table-column>
                            <el-table-column :label="'储值卡\n单价'" align="center" width="60" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.unitPrice + '/' + subDrugScope.row.specs.substring(subDrugScope.row.specs.length -1) }}
                              </template>
                            </el-table-column>
                            <el-table-column label="处方/药房取药" align="center" width="100" >
                              <el-table-column label="数量" align="center" width="110">
                                <template slot-scope="subDrugScope">
                                  <el-input size="mini" style="width: 90px;" v-model="subDrugScope.row.realQuantity" type="Number" min=0 @input="inputPackageDrugQuantity(subDrugScope.row, item.content)" :disabled="subDrugScope.row.status != 0" >
                                    <span slot="append">{{ subDrugScope.row.specs.substring(subDrugScope.row.specs.length -1) }}</span>
                                  </el-input>
                                </template>
                              </el-table-column>
                              <el-table-column :label="'单品金额'" align="center" width="75">
                                <template slot-scope="subDrugScope">
                                  {{ subDrugScope.row.realSalePrice }}
                                </template>
                              </el-table-column>
                              <el-table-column :label="'储值卡\n单品金额'" align="center" width="75">
                                <template slot-scope="subDrugScope">
                                  {{ subDrugScope.row.realSalePrice }}
                                </template>
                              </el-table-column>
                              <el-table-column label="用法" align="center" width="120">
                                <template slot-scope="subDrugScope">
                                  <el-select class="first-row" size="mini" v-model="subDrugScope.row.eachForDay" placeholder="请选择" :disabled="subDrugScope.row.status != 0">
                                    <el-option
                                      v-for="item in packageUsageModeEnum"
                                      :key="item"
                                      :label="item"
                                      :value="item">
                                    </el-option>
                                  </el-select>
                                  <el-input class="second-row" size="mini" v-model="subDrugScope.row.eachForTime" type="Number" min=0 @input="inputEachForTime(subDrugScope.row, item.content)" :disabled="subDrugScope.row.status != 0">
                                    <span slot="append">{{ subDrugScope.row.specs.substring(subDrugScope.row.specs.length -3, subDrugScope.row.specs.length -2) + '/次' }}</span>
                                  </el-input>
                                  <el-select class="third-row-select" size="mini" v-model="subDrugScope.row.eachForTimeInTime" placeholder="请选择" :disabled="subDrugScope.row.status != 0">
                                    <el-option
                                      label="餐前"
                                      value="餐前">
                                    </el-option>
                                    <el-option
                                      label="餐后"
                                      value="餐后">
                                    </el-option>
                                  </el-select>
                                </template>
                              </el-table-column>
                              <el-table-column label="上次购买时间" align="center" width="80">
                                <template slot-scope="subDrugScope">
                                  {{ subDrugScope.row.lastTime }}
                                </template>
                              </el-table-column>
                              <el-table-column label="备注" align="center" width="140" >
                                <template slot-scope="subDrugScope">
                                  <el-input type="textarea" v-model="subDrugScope.row.remark" :disabled="subDrugScope.row.status != 0" ></el-input>
                                </template>
                              </el-table-column>
                              <el-table-column label="活动" align="center" width="180">

                              </el-table-column>
                            </el-table-column>
                          </el-table>
                          <el-autocomplete
                            value-key="pinyinCode"
                            class="inline-input"
                            v-model="item.content.packageDrugSearchValue"
                            :fetch-suggestions="(queryString, cb) => queryDrugSearch(queryString, cb, item.content, 52)"
                            placeholder="请输入 整装药品 拼音简码"
                            :trigger-on-focus="false"
                            @select="(subDrug) => {handleDrugSelect(subDrug, 52, item.content)}"
                            style="width: 100%;"
                          >
                            <template slot-scope="{ item }">
                              <span >{{ item.code? item.code : '' }}</span>
                              <span >{{ item.commonName? '['+item.commonName+'] ' : '' }}</span>
                              <span >{{ item.name? item.name+' ' : '' }}</span>
                              <span >{{ item.specs? item.specs+' ' : ''  }}</span>
                              <span >{{ item.form? item.form+' ' : '' }}</span>
                              <span >{{ item.num? '库存:[' +item.num+'] ' : '库存:[0]' }}</span>
                              <!-- <span >{{ item.factory? item.factory+' ' : '' }}</span> -->
                              <span >{{ item.productTime ? '(' + item.productTime.split('T')[0] + '—' + item.expiration.split('T')[0] + ')' : '' }}</span>
                            </template>
                          </el-autocomplete>

                          <el-divider content-position="left">按处方/药房取药计算</el-divider>
                          <el-table
                            style="width: 100%;white-space: pre-wrap;"
                            :data="item.content.visitPackageDrugRealReport"
                            element-loading-text="Loading"
                            border
                            fit
                            :header-cell-style="{ height: '5px', padding: '0 0' }"
                          > 
                            <el-table-column label="处方金额" align="center" width="80">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="储值卡处方金额" align="center" width="120">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realCardAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="活动处方金额" align="center" width="120">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realActivityAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'活动+储值卡金额'" align="center" width="140">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.realActivityCardAmount }} <br>
                              </template>
                            </el-table-column>
                            
                          </el-table>

                          
                        </div>
                      </div>
                      <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                        <el-button type="primary" @click="confirmVisit(item.content, 5)" :disabled="item.content.status == 5 || item.content.status == 6">处方提交</el-button>
                      </div>
                    </el-collapse-item>
                    
                    <!-- <el-collapse-item title="诊中·预案填写" name="诊中·预案填写">
                      <h3>日常检查</h3>
                      <div class="body-item-contents">
                        <el-autocomplete
                          value-key="pinyinCode"
                          class="inline-input"
                          v-model="item.content.nextVisitDailySearchValue"
                          :fetch-suggestions="queryInspectionSearch"
                          placeholder="请输入 拼音简码"
                          :trigger-on-focus="false"
                          @select="(subDrug) => {handleDrugSelect(subDrug, 6, item.content)}"
                          style="width: 100%;"
                        >
                          <template slot-scope="{ item }">
                            <span >{{ item.name? item.name+'/' : '' }}</span>
                            <span >{{ item.commonName? item.commonName+' ' : '' }}</span>
                            <span >{{ item.form? item.form+' ' : '' }}</span>
                            <span >{{ item.specs? item.specs+' ' : ''  }}</span>
                            <span >{{ item.factory? item.factory+' ' : '' }}</span>
                            <span >{{ item.productTime ? '(' + item.productTime.split('T')[0] + '—' + item.expiration.split('T')[0] + ')' : '' }}</span>
                          </template>
                        </el-autocomplete>
                        <el-table
                          style="width: 100%;white-space: pre-wrap;"
                          :data="item.content.nextVisitDailyList"
                          element-loading-text="Loading"
                          border
                          fit
                        > 
                          <el-table-column label="序号" align="center" width="80">
                            <template slot-scope="inspectionScope">
                              {{ inspectionScope.$index+1 }}
                            </template>
                          </el-table-column>
                          <el-table-column :label="'商品编码'" width="100" align="center" prop="code"></el-table-column>
                          <el-table-column :label="'分装商品名称'" align="center" width="120">
                            <template slot-scope="inspectionScope">
                              <span>{{ '[' +inspectionScope.row.commonName + ']' }}</span><br>
                              <span>{{ inspectionScope.row.name }}</span><br>
                              <span>{{ inspectionScope.row.specs }}</span>
                            </template>
                          </el-table-column>
                          <el-table-column :label="'结果查询时长'" align="center" width="120" >
                            <template slot-scope="inspectionScope">
                              {{ inspectionScope.row.resultTime == '其他' ? inspectionScope.row.timeNumber + '小时' : inspectionScope.row.resultTime }}
                            </template>
                          </el-table-column>
                           <el-table-column :label="'单价'" align="center" width="70" >
                            <template slot-scope="inspectionScope">
                              {{ inspectionScope.row.unitPrice + '/' + inspectionScope.row.outerUnit }}
                            </template>
                          </el-table-column>
                          <el-table-column :label="'储值卡\n单价'" align="center" width="70" >
                            <template slot-scope="inspectionScope">
                              {{ inspectionScope.row.unitPrice + '/' + inspectionScope.row.outerUnit }}
                            </template>
                          </el-table-column>
                          <el-table-column label="数量" align="center" width="140">
                            <template slot-scope="inspectionScope">
                              <el-input v-model="inspectionScope.row.realQuantity" type="Number" min=0 @input="inputPackageDrugQuantity(inspectionScope.row, item.content)">
                                <span slot="append">{{ inspectionScope.row.outerUnit }}</span>
                              </el-input>
                            </template>
                          </el-table-column> 
                        </el-table>
                      </div>
                      <h3>医嘱检查</h3>
                      <div class="body-item-contents">
                        <el-autocomplete
                          value-key="pinyinCode"
                          class="inline-input"
                          v-model="item.content.nextVisitSearchValue"
                          :fetch-suggestions="queryInspectionSearch"
                          placeholder="请输入 拼音简码"
                          :trigger-on-focus="false"
                          @select="(subDrug) => {handleDrugSelect(subDrug, 7, item.content)}"
                          style="width: 100%;"
                        >
                          <template slot-scope="{ item }">
                            <span >{{ item.name? item.name+'/' : '' }}</span>
                            <span >{{ item.commonName? item.commonName+' ' : '' }}</span>
                            <span >{{ item.form? item.form+' ' : '' }}</span>
                            <span >{{ item.specs? item.specs+' ' : ''  }}</span>
                            <span >{{ item.factory? item.factory+' ' : '' }}</span>
                            <span >{{ item.productTime ? '(' + item.productTime.split('T')[0] + '—' + item.expiration.split('T')[0] + ')' : '' }}</span>
                          </template>
                        </el-autocomplete>
                        <el-table
                          style="width: 100%;white-space: pre-wrap;"
                          :data="item.content.nextVisitList"
                          element-loading-text="Loading"
                          border
                          fit
                        > 
                          <el-table-column label="序号" align="center" width="80">
                            <template slot-scope="inspectionScope">
                              {{ inspectionScope.$index+1 }}
                            </template>
                          </el-table-column>
                          <el-table-column :label="'商品编码'" width="100" align="center" prop="code"></el-table-column>
                          <el-table-column :label="'分装商品名称'" align="center" width="120">
                            <template slot-scope="inspectionScope">
                              <span>{{ '[' +inspectionScope.row.commonName + ']' }}</span><br>
                              <span>{{ inspectionScope.row.name }}</span><br>
                              <span>{{ inspectionScope.row.specs }}</span>
                            </template>
                          </el-table-column>
                          <el-table-column :label="'结果查询时长'" align="center" width="120" >
                            <template slot-scope="inspectionScope">
                              {{ inspectionScope.row.resultTime == '其他' ? inspectionScope.row.timeNumber + '小时' : inspectionScope.row.resultTime }}
                            </template>
                          </el-table-column>
                          <el-table-column :label="'单价'" align="center" width="70" >
                            <template slot-scope="inspectionScope">
                              {{ inspectionScope.row.unitPrice + '/' + inspectionScope.row.outerUnit }}
                            </template>
                          </el-table-column>
                          <el-table-column :label="'储值卡\n单价'" align="center" width="70" >
                            <template slot-scope="inspectionScope">
                              {{ inspectionScope.row.unitPrice + '/' + inspectionScope.row.outerUnit }}
                            </template>
                          </el-table-column>
                          <el-table-column label="数量" align="center" width="140">
                            <template slot-scope="inspectionScope">
                              <el-input v-model="inspectionScope.row.realQuantity" type="Number" min=0 @input="inputPackageDrugQuantity(inspectionScope.row, item.content)">
                                <span slot="append">{{ inspectionScope.row.outerUnit }}</span>
                              </el-input>
                            </template>
                          </el-table-column> 
                        </el-table>
                      </div>
                      <h3>预案备注</h3>
                      <el-input type="textarea" v-model="item.content.nextVisitRemark" rows=5 ></el-input>
                      <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                        <el-button type="primary" @click="confirmVisit(item.content, 6)">预案提交</el-button>
                      </div>
                    </el-collapse-item>  -->
                    
                  </el-collapse>

                </div>

                </el-tab-pane>
              </el-tabs>

            </el-main>
            <el-aside width="220px">
              <el-menu
                @select="(key, keyPath) => handleMenuSelect(key, keyPath, item.content)" 
                default-active="2"
                :default-openeds="defaultOpen"
                class="el-menu-vertical-demo"
                @open="handleOpen"
                @close="handleClose">
                <el-submenu index="会员管理" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">会员管理</span>
                  </template>
                    <el-menu-item index="会员基础信息查询" style="font-size: 14px">会员基础信息查询</el-menu-item>
                </el-submenu>
                <el-submenu index="诊中处置" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">诊中处置</span>
                  </template>
                    <el-menu-item index="诊中·诊室检查开立" style="font-size: 14px">诊中·诊室检查开立</el-menu-item>
                    <el-menu-item index="诊中·实验室检查开立" style="font-size: 14px">诊中·实验室检查开立</el-menu-item>
                    <el-menu-item index="诊中·信息采集" style="font-size: 14px">诊中·信息采集</el-menu-item>
                    <el-menu-item index="诊中·诊断开具" style="font-size: 14px">诊中·诊断开具</el-menu-item>
                    <el-menu-item index="诊中·处方开具" style="font-size: 14px">诊中·处方开具</el-menu-item>
                    <el-menu-item index="诊中·预案填写" style="font-size: 14px">诊中·预案填写</el-menu-item>
                </el-submenu>
                <el-submenu index="会员就诊记录查询" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">会员就诊记录查询</span>
                  </template>
                    <el-menu-item index="会员就诊记录查询" style="font-size: 14px">会员就诊记录查询</el-menu-item>
                </el-submenu>
                <el-submenu index="缴费/卡/券" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">缴费/卡/券</span>
                  </template>
                    <el-menu-item index="会员缴费/卡/券记录查询" style="font-size: 14px">会员缴费/卡/券记录查询</el-menu-item>
                </el-submenu>
                <el-submenu index="租借药盒" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">租借药盒</span>
                  </template>
                    <el-menu-item index="会员租借药盒记录查询" style="font-size: 14px">会员租借药盒记录查询</el-menu-item>
                </el-submenu>
              </el-menu>
            </el-aside>
          </el-container>
        </div>

      </el-tab-pane>
      </el-tabs>
    
  </div>
</template>

<script>

import { getList as getPatientList, add, edit, del, getAllPatientList} from '@/api/patient'
import { regionData } from 'element-china-area-data'
import { getAllUserList} from '@/api/user'
import { getList as getSourceList} from '@/api/source'
import { getList, addOrUpdate, guidanceWaitingNumber, getJobStatusList} from '@/api/guidance'
import { getListByPinyinCode, queryByCodeAnDepositoryId, getListByPinyinCodeProductTime, queryByCodes } from '@/api/drug'
import { queryDepositoryIdsByOptType } from '@/api/drugDepositoryAuth'
import Decimal from 'decimal.js';
import { add as addNextVisit, edit as editNextVisit} from '@/api/nextVisit'
import { add as addVisit, detail as detailVisit, updateVisitStatus, detailVisitDrug } from '@/api/visit'
import { add as addVisitDrug } from '@/api/visitDrug'
import { add as addInspection, getInspectionByGuidanceCode} from '@/api/visitInspection'
import { getLastNextVisit } from '@/api/nextVisit'
import { addDate, stringToDate, dateToString, betweenDate, subDate } from '../../utils/dateUtil'

export default {
  name: "VisitList",
  filters: {
    birthdayTypeFilter(status) {
      const statusMap = ['', '阳', '阴']
      return statusMap[status]
    },
    statusColorFilter(status) {
      const statusMap = ['', '', '', '', '', 'success', 'info']
      return statusMap[status]
    },
    statusFilter(status) {
      const statusMap = ['候诊', '就诊中', '待检查', '待缴费', '待取药', '已完成', '中止']
      return statusMap[status]
    }
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (!value) callback(new Error('请输入姓名')) 
      else callback()
    }
    return {
      list: [],
      listLoading: true,
      patientList: null,
      patientListLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      addPatientformVisible: false,
      info: {},
      addPatientForm: {},
      query: {},
      dialogTitle: '添加来源',
      depts:[],
      editableTabsValue: '诊中列表',
      editableTabs: [],
      patientTabsValue: '',
      patientTabs: [],
      sourceEnum: [],
      sexEnum: ["男", "女"],
      userEnum: [],
      patientEnum: [],
      options: regionData,
      birthdayTypeEnum:[{id: 1, name: '公历'}, {id: 2, name: '农历'}],
      multiAddressDesEnum: ["临时居住", "子女居所", "邮寄用地址", "其他"],
      deptEnum: ['劳动店', '永春店'],
      introducerDisable: true,
      defaultOpen: ['会员管理', '诊中处置', '会员就诊记录查询', '缴费/卡/券', '租借药盒'],
      meteredEnum: [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3],
      usageModeEnum: ['1次/早', '1次/中', '1次/晚'],
      packageUsageModeEnum: ['1次/天', '2次/天', '3次/天', '4次/天', '5次/天'],
      usagePurposeEnum: ['日常', '日常特', '备用', '补'],
      visitTitleEnum: ['诊中·诊室检查开立', '诊中·实验室检查开立', '诊中·信息采集', '诊中·诊断开具', '诊中·处方开具', '诊中·预案填写',],
      jobStatusList: [],
      jobStatusGuidance: {},
      jobStatusDrug: {},
      pickerOptions: {
        disabledDate: time => {
          return (
            //new Date(this.timeDate.endTime).getTime()<= time.getTime() 
            time.getTime() <= subDate(new Date(), 'day', 1).getTime()
          );
        }
      },
      initDepositoryNum: []  // 初始库存

    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      var loginInfo = this.$store.getters.userInfo.loginInfo
      console.log("loginInfo", loginInfo)
      var deptId = loginInfo.loginDept ? loginInfo.loginDept.deptId : undefined
      // var workAddressId = loginInfo.loginWorkAddress.id
      var jobOfficeId = loginInfo.loginJobOffice?loginInfo.loginJobOffice.jobOfficeId:undefined
      this.initListData(deptId, jobOfficeId)
      guidanceWaitingNumber({deptId: deptId, workAddressId: undefined, jobOfficeId: jobOfficeId}).then(res=> {
        this.reports = res.data
      })

      getSourceList().then(sourceRes=>{
        this.sourceEnum = sourceRes.data
      })
      getAllPatientList().then(res=>{
        console.log("patient res:", res)
        this.patientEnum = res.data
      })
      getAllUserList().then(res=>{
        console.log("user res:", res)
        this.userEnum = res.data
      })
      getJobStatusList({deptId}).then(res=> {
        console.log('jobStatusList', res)
        this.jobStatusList = res.data
      })
      // 会员查询tab
      this.getPatientList({})
      this.editableTabs.push({
        title: '会员查询',
        name: '会员查询',
        content: {},
        isClose: false,
      })
      // this.editableTabsValue = '会员查询'
    },
    initListData(deptId, jobOfficeId) {
      getList({currentPage: this.currentPage, pageSize: this.pageSize, deptId: deptId, jobOfficeId: jobOfficeId}).then(res=>{
        console.log(res.data)
        this.list = res.data.records
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
    },
    selectVisitInspectionCard(patient) {
      console.log('patient--', patient)
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    getInfo(row) {
      this.info = row
      this.infoVisible = true
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改来源'
      this.form = JSON.parse(JSON.stringify(row))
      this.formVisible = true
    },
    
    cancel() {
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
    },
    removePatientTab(targetName, patient) {
      let tabs = patient.patientTabs;
      let activeName = patient.patientTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      patient.patientTabsValue = activeName;
      patient.patientTabs = tabs.filter(tab => tab.name !== targetName);
    },
    queryPatient() {
      var list = this.editableTabs.filter(item => item.name == '会员查询')
      if(list.length != 0) {
        this.editableTabsValue = '会员查询'
        return
      }
      this.getPatientList({})
      this.editableTabs.push({
        title: '会员查询',
        name: '会员查询',
        content: {},
      })
      this.editableTabsValue = '会员查询'
    },
    search() {
      this.getPatientList({name: this.query.name})
    },    
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //  get patient list page function
    getPatientList(params) {
      this.patientListLoading = true
      params.currentPage = this.currentPage
      params.pageSize = this.pageSize 
      getPatientList(params).then(res=>{
        this.patientList = res.data.records
        console.log(this.patientList)
        this.patientList.forEach(item=>{
          item.age = new Date().getFullYear() - item.birthday.substring(0,4)
          item.addressList.forEach(address=>{
            var addressPreArr = address.address.split('|||')
            address.addressPre = [addressPreArr[0], addressPreArr[1], addressPreArr[2]]
            this.$set(address, 'addressMid', addressPreArr[3])
            this.$set(address, 'addressInfo', addressPreArr[4])
          })
        })
        this.patientListLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.patientListLoading = false
      })
      
    },
   
    handleChange (address) {
      this.$set(this.addPatientForm, 'addressPre', address)
    },
    addAddress() {
      this.addPatientForm.addressList.push({})
    },
    deleteAddress(address, list) {
      list.splice(list.indexOf(address), 1);
    },
    updateFormAddAddress(updateForm) {
      updateForm.addressList.push({})
    },
    changeBirthday() {

    },
    changeMultiAddressDes(item, address) {
      if(item == '其他')  {
        this.$set(address, 'isOtherAddress', 1)
      } else {
        this.$set(address, 'isOtherAddress', 0)
      }
    },
    confirm() {
      this.$refs.addPatientForm[0].validate(valid => {
        if (valid) {
          console.log(this.addPatientForm)
          this.addPatientForm.addressList.forEach(address=>{
            address.address = address.addressPre[0] + ' ' + address.addressPre[1] + ' ' + address.addressPre[2] + ' ' + address.addressMid + ' ' + address.addressInfo
          })
          add(this.addPatientForm).then(res=>{
            console.log(res)
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.editableTabsValue = "1"
          }).catch(err=>{
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    updateConfirm(updateForm) {
      // this.$refs.updatePatientForm[0].validate(valid => {
      //   if (valid) {
          console.log(updateForm)
          updateForm.addressList.forEach(address=>{
            address.address = address.addressPre[0] + ' ' + address.addressPre[1] + ' ' + address.addressPre[2] + ' ' + address.addressMid + ' ' + address.addressInfo
          })
          edit(updateForm).then(res=>{
            console.log(res)
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.editableTabsValue = "1"
          }).catch(err=>{
            console.log(err)
          })
        // } else {
        //   console.log('error submit!!')
        //   return false
        // }
      // })
    },
    optionPatient(patient) {
      var list = this.editableTabs.filter(item => item.name == patient.code)
      this.initPatientVisitData(patient, list)
    },
    optionVisit(visit) {
      getPatientList({name: visit.patientCode, currentPage: 1, pageSize: 1}).then(res=> {
        console.log("get patient list res===>", res)
        var patient = res.data.records[0]
        patient.guidanceCode = visit.guidanceCode
        patient.status = visit.status
        var list = this.editableTabs.filter(item => item.name == patient.code)
        this.initPatientVisitData(patient, list)
        // 更新就诊状态
        updateVisitStatus({guidanceCode: visit.guidanceCode}).then(updateStatusRes=> {
          var loginInfo = this.$store.getters.userInfo.loginInfo
          var deptId = loginInfo.loginDept ? loginInfo.loginDept.deptId : undefined
          var jobOfficeId = loginInfo.loginJobOffice?loginInfo.loginJobOffice.jobOfficeId:undefined
          this.initListData(deptId, jobOfficeId)
        })
      })
    },
    async initPatientVisitData(patient, list) {
      if(list.length != 0) {
        this.editableTabsValue = patient.code
        return
      }
      this.$set(patient, 'patientTabsValue', '诊中处置')
      this.$set(patient, 'patientTabs', [{
        title: '诊中处置',
        name: '诊中处置',
        content: {}
      }])
      this.$set(patient, 'visit', {})
      this.$set(patient, 'visitActiveName', '')
      this.$set(patient, 'visitSubPackageDrugList', [])
      this.$set(patient, 'visitSubPackageDrugPlanReport', [{title: '本次'}])
      this.$set(patient, 'visitSubPackageDrugRealReport', [{title: '本次'}])
      this.$set(patient, 'visitPackageDrugRealReport', [{PLAN_AMOUNT: '处方金额', CARD_PLAN_AMOUNT: '储值卡处方金额', ACTIVITY_PLAN_AMOUNT: '活动处方金额', ACTIVITY_CARD_PLAN_AMOUNT: '活动+储值卡金额'}])
      this.$set(patient, 'visitPackageDrugList', [])
      this.$set(patient, 'visitInspectionCard', undefined)
      this.$set(patient, 'nextVisitDailyList', [])
      this.$set(patient, 'nextVisitList', [])
      this.$set(patient, 'visitInspectionRealReport', [{guidanceCode: patient.guidanceCode, PLAN_AMOUNT: '处方金额', CARD_PLAN_AMOUNT: '储值卡处方金额', ACTIVITY_PLAN_AMOUNT: '活动处方金额', ACTIVITY_CARD_PLAN_AMOUNT: '活动+储值卡金额'}])
      // 先mock 卡数据 TODO  卡功能完善后从后端取值
      this.$set(patient, 'card', [{id: 1, name: '1000送200'}])
      this.$set(patient, 'cardList', [{id: 1, name: '1000送200'}, {id: 2, name: '2000送500'}, {id: 3, name: '28天期限卡'}])
      // 新增就诊信息，进入就诊状态
      this.initVisit(patient)
      const inspectionList = await this.initInspectionList(patient)
      this.$set(patient, 'visitInspectionList', inspectionList)
      this.inputRealQuantity(patient)
      detailVisitDrug({guidanceCode: patient.guidanceCode}).then(visitDrugRes => {
        console.log('visitDrugRes', visitDrugRes)
        this.$set(patient, 'visitSubPackageDrugList', visitDrugRes.data.visitSubPackageDrugList)
        this.$set(patient, 'visitSubPackageDrugPlanReport', visitDrugRes.data.visitSubPackageDrugPlanReport ? [visitDrugRes.data.visitSubPackageDrugPlanReport] : [{title: '本次'}])
        this.$set(patient, 'visitSubPackageDrugRealReport', visitDrugRes.data.visitSubPackageDrugRealReport ? [visitDrugRes.data.visitSubPackageDrugRealReport] : [{title: '本次'}])
        this.$set(patient, 'visitPackageDrugList', visitDrugRes.data.visitPackageDrugList)
        this.$set(patient, 'visitPackageDrugRealReport', visitDrugRes.data.visitPackageDrugRealReport ? [visitDrugRes.data.visitPackageDrugRealReport] : [{}])
        this.$set(patient, 'visit', visitDrugRes.data.visit)
      })

      this.editableTabs.push({
        title: patient.name,
        name: patient.code,
        content: patient,
        isClose: true
      })
      this.editableTabsValue = patient.code
    },
    initVisit(patient) {
      const userInfo = this.$store.getters.userInfo
      detailVisit({guidanceCode: patient.guidanceCode}).then(detailRes=> {
        if(detailRes.data) {
          console.log('visit detailRes', detailRes)
          this.$set(patient, 'visit', detailRes.data)
        } else {
          this.$set(patient, 'visit', {
            guidanceCode: patient.guidanceCode,
            patientId: patient.id,
            doctorId: userInfo.id
          })
          addVisit({visit: patient.visit}).then(res => {
            console.log('add visit res', res)
            patient.visit.id = res.data.id
          })
        }
      })
      
    },
    async initInspectionList(patient) {
      const inspectionInfoRes = await getInspectionByGuidanceCode({guidanceCode: patient.guidanceCode})
      console.log("get inspectionRes",inspectionInfoRes.data)
      // 如果已开检查 加载已开
      if(inspectionInfoRes.data && inspectionInfoRes.data.length != 0) {
        for (const element of inspectionInfoRes.data) {
          element.operation = Number(element.operation)
        }
        console.log('patient.visitInspectionList', inspectionInfoRes.data);
        return inspectionInfoRes.data
      } else {  // 如果没开检查 加载上次预案
        return inspectionInfoRes.data
        // 预案功能 一期先不上
        getLastNextVisit({userId: patient.id}).then(res=> {
          if(res.data) {
            var nextVisitDailyList = JSON.parse(res.data.nextVisitDailyList)
            var nextVisitList = JSON.parse(res.data.nextVisitList)
            var drugEnum = []
            if(nextVisitDailyList && nextVisitDailyList.length != 0) {
              var query = {drugCodes: nextVisitDailyList.map(obj=> obj.code).join(',')}
              queryByCodes(query).then(drugRes=> {
                drugEnum.push(...drugRes.data)
                nextVisitDailyList.forEach(dailyInspection => {
                  var drug = drugEnum.filter(drug=> drug.code == dailyInspection.code)[0]
                  drug.realQuantity = 1
                  drug.source = '日常检查'
                  drug.id = undefined
                  drug.status = 0
                  patient.visitInspectionList.push(JSON.parse(JSON.stringify(drug)))
                  this.inputRealQuantity(patient)
                })
                if(nextVisitList && nextVisitList.length != 0) {
                  queryByCodes({drugCodes: nextVisitList.map(obj=> obj.code).join(',')}).then(drugRes=> {
                    drugEnum.push(...drugRes.data)
                    nextVisitList.forEach(dailyInspection => {
                      var drug = drugEnum.filter(drug=> drug.code == dailyInspection.code)[0]
                      drug.realQuantity = 1
                      drug.source = '医嘱检查'
                      drug.id = undefined
                      drug.status = 0
                      patient.visitInspectionList.push(JSON.parse(JSON.stringify(drug)))
                      this.inputRealQuantity(patient)
                    })
                  })
                }
              })
            } else {
              if(nextVisitList && nextVisitList.length != 0) {
                queryByCodes({drugCodeList: nextVisitList}).then(drugRes=> {
                  drugEnum.push(...drugRes.data)
                  nextVisitList.forEach(dailyInspection => {
                    var drug = drugEnum.filter(drug=> drug.code == dailyInspection.code)[0]
                    drug.realQuantity = 1
                    drug.source = '医嘱检查'
                    drug.id = undefined
                    drug.status = 0
                    patient.visitInspectionList.push(JSON.parse(JSON.stringify(drug)))
                    this.inputRealQuantity(patient)
                  })
                })
              }
            }
          }
        })
      }
    },

    /** patient detail page function */
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    handleMenuSelect(key, keyPath, patient) {
      console.log(keyPath)
      var tabValue = keyPath[0]
      console.log(tabValue)
      this.$set(patient, 'visitActiveName', keyPath[1])
      var list = patient.patientTabs.filter(item => item.name == tabValue)
      if(list.length != 0) {
        patient.patientTabsValue = tabValue
        return
      }

      patient.patientTabs.push({
        title: tabValue,
        name: tabValue,
        content: {}
      })
      patient.patientTabsValue = tabValue
    },

    /** visit page */
    tableRowClassName({row, rowIndex}) {
      if (row.status === 0 && row.remainderTime === 0) {
        return 'warning-row';
      } else if (row.status != 0) {
        return 'done-row';
      }
      return '';
    },
    inputStartTime(patient) {
      if(patient.visit.planUsageDays) {
        var endUsageTime = addDate(patient.visit.startUsageTime, 'day', patient.visit.planUsageDays)
        this.$set(patient.visit, 'endUsageTime', endUsageTime)
      }
    },
    queryDrugSearch(queryString, cb, patient, type) {
      if(!queryString || queryString.trim() == '') {
        cb([])
        return
      }
      queryDepositoryIdsByOptType({optType: 2}).then(res=> {
        if(res.data.length == 0) {
          this.$message.error('无销售权限')
          cb([{name: '无销售权限'}])
          return
        }
        getListByPinyinCodeProductTime(queryString, res.data, type).then(drugListRes=>{
          console.log("subDrugListRes", drugListRes)
          for (const element of drugListRes.data) {
            element.uniqueKey = element.code + (element.productTime?element.productTime.substr(0,10):'') + (element.expiration?element.expiration.substr(0,10):'')
          }
          this.checkDepositoryNumOnQuery(drugListRes.data, patient.visitSubPackageDrugList)
          // 调用 callback 返回建议列表的数据
          cb(drugListRes.data);
        })
      })
    },
    // 选用量时 此药原库存 - 当前处方此药已开数量
    checkDepositoryNumOnEachUsageAmount(list, index) {
      var row = list[index]
      var drugListByCode = list.filter(item=> item.uniqueKey == row.uniqueKey && item.planQuantity)
      var sumPlanQuantity = drugListByCode.reduce((sum, obj) => sum + Number(obj.planQuantity), 0)
      console.log('row', row)
      var initDepositoryNumObj = this.initDepositoryNum.find(item=> item.uniqueKey = row.uniqueKey)
      console.log('this.initDepositoryNum', this.initDepositoryNum)
      console.log('check depository num', initDepositoryNumObj)
      if(!initDepositoryNumObj.initNum) return true // 无库存的药品
      if(initDepositoryNumObj.initNum < sumPlanQuantity) {
        this.$alert('库存不足', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        this.$set(row, 'planUsageDays', undefined)
        this.$set(row, 'planQuantity', undefined)
        this.$set(row, 'planSalePrice', undefined)
        this.$set(row, 'realUsageDays', undefined)
        this.$set(row, 'realQuantity', undefined)
        this.$set(row, 'realSalePrice', undefined)
        this.$set(row, 'eachUsageAmount', undefined)
        return false
      }
      return true
    },
    // 选药时 此药原库存-当前处方此药已开数量 （TODO 要换算）
    checkDepositoryNumOnQuery(queryList, visitSubPackageDrugList) {
      if (queryList.length == 0 || visitSubPackageDrugList.length == 0) return
      for (const queryElement of queryList) {
        for (const subDrugListElement of visitSubPackageDrugList) {
          if(queryElement.uniqueKey == subDrugListElement.uniqueKey && subDrugListElement.realQuantity) {
            queryElement.num = queryElement.num - subDrugListElement.realQuantity
          }
        }
      }
    },
    handleDrugSelect(item, type, patient) {
      if(!item.code) return
      this.$set(patient, 'subPackageDrugSearchValue', '') // 清空分装搜索框
      this.$set(patient, 'packageDrugSearchValue', '') // 清空整装搜索框
      this.$set(patient, 'inspectionSearchValue', '') // 清空实验室检查搜索框
      if(item.num !== undefined && item.num <= 0) {
        console.log('handle item', item.num <= 0)
        this.$alert(item.code + '[' + item.commonName + ']' +'库存不足, 库存数量:[' + item.num + ']', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return
      }
      item.id = undefined
      if(!this.initDepositoryNum.map(el=> el.code).includes(item.code)) {
        this.initDepositoryNum.push({code: item.code, uniqueKey: item.uniqueKey, initNum: item.num, tmpNum: item.num})
      }
      if (type == 1) {

      } else if (type == 2) {
        item.source = "添加"
        item.realQuantity = 1
        item.status = 0
        item.guidanceCode = patient.guidanceCode
        this.$set(item, 'totalPrice1', item.realQuantity ? Decimal(item.realQuantity).mul(item.unitPrice) : 0)
        this.$set(item, 'totalPrice2', item.realQuantity ? Decimal(item.realQuantity).mul(item.unitPrice) : 0)
        patient.visitInspectionList.push(item)
        this.inputRealQuantity(patient)
        patient.inspectionSearchValue = ''

      }  else if (type == 3) {
        
      }  else if (type == 4) {

      } else if(type == 51) {  // 分装
        item.usagePurpose = '日常'
        item.status = 0
        item.serialNum = this.buildSerialNum(patient.visitSubPackageDrugList)
        item.isReserve = false
        if(patient.visit.planUsageDays) {
          item.planUsageDays = patient.visit.planUsageDays
          item.realUsageDays = patient.visit.planUsageDays
        }
        // 如果有空行 优先添加到空行里 （空行是添加的分组）
        for (let tmpIndex = 0; tmpIndex < patient.visitSubPackageDrugList.length; tmpIndex++) {
          if(!patient.visitSubPackageDrugList[tmpIndex].code) {
            const tmpElement = patient.visitSubPackageDrugList[tmpIndex]
            item.serialNum = tmpElement.serialNum  // 编号不变
            item.isDisabledPlanUsageDays = tmpElement.isDisabledPlanUsageDays  // 是否可输入处方天数不变
            // 如果有 处方天数 片/次  次/天  不变
            item.planUsageDays = tmpElement.planUsageDays ? tmpElement.planUsageDays : 0
            item.realUsageDays = tmpElement.planUsageDays ? tmpElement.planUsageDays : 0
            item.eachUsageAmount = tmpElement.eachUsageAmount
            item.planQuantity = tmpElement.planQuantity
            item.usageMode = tmpElement.usageMode
            // 校验库存
            if(item.num < item.planQuantity) {
              this.$alert('库存不足', '错误', {
                confirmButtonText: '确定',
                type: 'error',
              });
              return
            }
            // 计算金额
            this.updatePrice(item)
            patient.visitSubPackageDrugList.splice(tmpIndex, 1, JSON.parse(JSON.stringify(item)));
            return
          }
        }
        item.isDisabledPlanUsageDays = true
        console.log('item', item)
        patient.visitSubPackageDrugList.push(JSON.parse(JSON.stringify(item)))
      } else if(type == 52) { // 整装
        item.status = 0
        patient.packageDrugSearchValue = ''
        patient.visitPackageDrugList.push(JSON.parse(JSON.stringify(item)))
      } else if(type == 6) {
        patient.nextVisitDailySearchValue =''
        patient.nextVisitDailyList.push(JSON.parse(JSON.stringify(item)))
      } else if(type == 7) {
        patient.nextVisitDailySearchValue =''
        patient.nextVisitList.push(JSON.parse(JSON.stringify(item)))
      }

    },
    buildSerialNum(list) {
      if(!list || list.length == 0) {
        return 1
      }
      var lastSerialNum = list[list.length - 1].serialNum
      return Number(Math.floor(lastSerialNum)) + Number(1)
    },
    selectEachUsageAmount(eachUsageAmount, subDrugScope, patient) {
      if(subDrugScope.planUsageDays) {
        if(!Number.isInteger(subDrugScope.planUsageDays * eachUsageAmount)) {
          subDrugScope.eachUsageAmount = undefined
          this.initPlanQuantity(subDrugScope)
          this.$alert('处方出现小数，请重新选择', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return
        }
        this.$set(subDrugScope, 'planQuantity', subDrugScope.planUsageDays * eachUsageAmount)
        console.log('planQuantity', subDrugScope.planQuantity)
        // 校验库存
        if(!this.checkDepositoryNumOnEachUsageAmount(patient.visitSubPackageDrugList, patient.visitSubPackageDrugList.indexOf(subDrugScope))) {
          return
        }
        this.$set(subDrugScope, 'planSalePrice', subDrugScope.planUsageDays * eachUsageAmount)
        console.log('planSalePrice', subDrugScope.planSalePrice)
        
        if(subDrugScope.planQuantity && Number(subDrugScope.planQuantity) > Number(subDrugScope.num)) {
          subDrugScope.eachUsageAmount = undefined
          this.initPlanQuantity(subDrugScope)
          this.$alert(subDrugScope.code + '[' + subDrugScope.commonName + ']' +'库存不足, 库存数量:[' + subDrugScope.num + ']', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return
        }
        this.updatePrice(subDrugScope)
        this.updateSubPackageReports(patient)
      }
    },
    blurPatientPlanUsageDays(patient) {
      patient.visitSubPackageDrugList.forEach(subDrugScope=> {
        if(subDrugScope.eachUsageAmount) {
          if(!Number.isInteger(Number(patient.visit.planUsageDays * subDrugScope.eachUsageAmount))) {
            patient.visit.planUsageDays = undefined
            this.initPlanQuantity(subDrugScope)
            this.$alert('处方出现小数，请重新输入', '错误', {
              confirmButtonText: '确定',
              type: 'error',
            });
            return
          }
          
          this.$set(subDrugScope, 'planQuantity', subDrugScope.planUsageDays * subDrugScope.eachUsageAmount)
          if(!this.checkDepositoryNumOnEachUsageAmount(patient.visitSubPackageDrugList, patient.visitSubPackageDrugList.indexOf(subDrugScope))) {
            return 
          }
          this.$set(subDrugScope, 'planSalePrice',  (subDrugScope.planQuantity * subDrugScope.unitPrice).toFixed(2))
          var reserveNum = subDrugScope.reserveNum && subDrugScope.planUsageDays != 0 ? subDrugScope.reserveNum : 0
          this.$set(subDrugScope, 'realUsageDays', subDrugScope.planUsageDays)
          this.$set(subDrugScope, 'realSalePrice',  (subDrugScope.realQuantity * subDrugScope.unitPrice).toFixed(2))
          this.$set(subDrugScope, 'realQuantity', subDrugScope.realUsageDays * subDrugScope.eachUsageAmount - reserveNum)

        }
      })
    },
    inputPatientPlanUsageDays(patient) {
      patient.visit.planUsageDays = Number(patient.visit.planUsageDays)
      if(patient.visit.planUsageDays > 99) patient.visit.planUsageDays = 99
      if(patient.visit.planUsageDays < 0) patient.visit.planUsageDays = 0
      if(patient.visit.startUsageTime) {
        var endUsageTime = addDate(new Date(patient.visit.startUsageTime), 'day', patient.visit.planUsageDays)
        this.$set(patient.visit, 'endUsageTime', endUsageTime)
      }
      patient.visitSubPackageDrugList.forEach(subDrugScope=> {
        if(subDrugScope.usagePurpose == '日常' || subDrugScope.usagePurpose == '日常特' ) {
          this.$set(subDrugScope, 'planUsageDays', 0)
          this.$set(subDrugScope, 'realUsageDays', 0)
          if(new Decimal(subDrugScope.serialNum).isInteger() && !subDrugScope.isGroup) {
            this.$set(subDrugScope, 'planUsageDays', patient.visit.planUsageDays)
            this.$set(subDrugScope, 'realUsageDays', patient.visit.planUsageDays)
          }
          this.$set(subDrugScope, 'planUsageStartDays', 0)
          this.$set(subDrugScope, 'planUsageDaysInfo', '')
          
        }
        if(subDrugScope.eachUsageAmount && subDrugScope.unitPrice) {
          
          this.$set(subDrugScope, 'planQuantity', subDrugScope.planUsageDays * subDrugScope.eachUsageAmount)
          this.$set(subDrugScope, 'planSalePrice',  (subDrugScope.planQuantity * subDrugScope.unitPrice).toFixed(2))
          var reserveNum = subDrugScope.reserveNum && subDrugScope.planUsageDays != 0 ? subDrugScope.reserveNum : 0
          this.$set(subDrugScope, 'realUsageDays', subDrugScope.planUsageDays)
          this.$set(subDrugScope, 'realQuantity', subDrugScope.realUsageDays * subDrugScope.eachUsageAmount - reserveNum)
          this.$set(subDrugScope, 'realSalePrice',  (subDrugScope.realQuantity * subDrugScope.unitPrice).toFixed(2))

        }
      })
      this.updateSubPackageReports(patient)
    },
    updatePrice(subDrugScope) {
      if (subDrugScope.planQuantity && subDrugScope.unitPrice) {
        this.$set(subDrugScope, 'planSalePrice',  (subDrugScope.planQuantity * subDrugScope.unitPrice).toFixed(2))
        var reserveNum = subDrugScope.reserveNum && subDrugScope.planUsageDays != 0 ? subDrugScope.reserveNum : 0
        this.$set(subDrugScope, 'realUsageDays', subDrugScope.planUsageDays)
        this.$set(subDrugScope, 'realQuantity', subDrugScope.realUsageDays * subDrugScope.eachUsageAmount - reserveNum)
        this.$set(subDrugScope, 'realSalePrice',  (subDrugScope.realQuantity * subDrugScope.unitPrice).toFixed(2))
      }
    },
    updateSubPackageReports(patient) {
      var curPlanReport = patient.visitSubPackageDrugPlanReport[patient.visitSubPackageDrugPlanReport.length -1]
      var curRealReport = patient.visitSubPackageDrugRealReport[patient.visitSubPackageDrugRealReport.length -1]
      var planAmount = new Decimal(0)
      var realAmount = new Decimal(0)
      patient.visitSubPackageDrugList.forEach(subDrug=> {
        if(subDrug.planQuantity) {
          var tmpPlanAmount = subDrug.planQuantity? subDrug.planQuantity * subDrug.unitPrice : 0
          var tmpRealAmount = subDrug.realQuantity? subDrug.realQuantity * subDrug.unitPrice : 0
          planAmount = planAmount.plus(new Decimal(tmpPlanAmount))
          realAmount = realAmount.plus(new Decimal(tmpRealAmount))
        }
      })
      this.$set(curPlanReport, 'planAmount', planAmount.toFixed(2, Decimal.ROUND_DOWN))
      this.$set(curRealReport, 'realAmount', realAmount.toFixed(2, Decimal.ROUND_DOWN))
      this.$set(curRealReport, 'guidanceCode', patient.guidanceCode)
      if(patient.visit.planUsageDays) {
        this.$set(curPlanReport, 'planUsageDays', patient.visit.planUsageDays)
        this.$set(curRealReport, 'realUsageDays', patient.visit.planUsageDays)
        this.$set(curPlanReport, 'planAmountInDay', planAmount.div(new Decimal(patient.visit.planUsageDays)).toFixed(2, Decimal.ROUND_DOWN))
        this.$set(curRealReport, 'realAmountInDay', realAmount.div(new Decimal(patient.visit.planUsageDays)).toFixed(2, Decimal.ROUND_DOWN))
        this.$set(curPlanReport, 'planAmountInMonth', planAmount.div(new Decimal(28)).toFixed(2, Decimal.ROUND_DOWN))
        this.$set(curRealReport, 'realAmountInMonth', realAmount.div(new Decimal(28)).toFixed(2, Decimal.ROUND_DOWN))
        if(patient.planReportsDay) {
          this.$set(curPlanReport, 'planAmountInplanReportsDay', planAmount.div(new Decimal(patient.planReportsDay)).toFixed(2, Decimal.ROUND_DOWN))
        }
        if(patient.realReportsDay) {
          this.$set(curRealReport, 'realAmountInRealReportsDay', realAmount.div(new Decimal(patient.realReportsDay)).toFixed(2, Decimal.ROUND_DOWN))
        }
      }
    },
    blurSubDrugPlanUsageDays(index, patient) {
      var list = patient.visitSubPackageDrugList
      var row = list[index]
      if(row.eachUsageAmount && !Number.isInteger(row.planUsageDays * row.eachUsageAmount)) {
        row.planUsageDays = undefined
        row.planUsageDaysInfo = undefined
        this.initPlanQuantity(row)
        this.$alert('处方出现小数，请重新输入', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return
      }
      if(row.planQuantity && Number(row.planQuantity) > Number(row.num)) {
        row.planUsageDays = undefined
        row.planUsageDaysInfo = undefined
        this.initPlanQuantity(row)
        this.$alert('库存不足, 库存数量:[' + row.num + ']', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return
      }
      if (row.usagePurpose == '日常') {
        // 如果是倒数第二个，则自动算出最后一个天数
        if(list[index+1] && !new Decimal(list[index+1].serialNum).isInteger()   // 下一个有值 且非整数
        && (!list[index+2] || list[index+2] && new Decimal(list[index+2].serialNum).isInteger())) { // 且 下下一个没有值或有值为整数
          var groupItemList = this.getCurGroupList(index, list)
          var PlanUsageDaysSum = 0
          for (let index = 0; index < groupItemList.length - 1; index++) {
            PlanUsageDaysSum = Number(PlanUsageDaysSum) + Number(groupItemList[index].planUsageDays)
          }
          var lastItem = groupItemList[groupItemList.length - 1]
          // 校验最后一行库存
          const planQuantity = Number(patient.visit.planUsageDays) < Number(PlanUsageDaysSum) ? 0 : patient.visit.planUsageDays - PlanUsageDaysSum
          this.$set(lastItem, 'planUsageDays', planQuantity)
          if(lastItem.eachUsageAmount) {
            this.$set(lastItem, 'planQuantity', lastItem.planUsageDays * lastItem.eachUsageAmount)
            if(!this.checkDepositoryNumOnEachUsageAmount(list, index)){
              this.$set(lastItem, 'planUsageDays', undefined)
              this.$set(lastItem, 'planQuantity', undefined)
              this.$set(lastItem, 'planSalePrice', undefined)
              this.$set(lastItem, 'realUsageDays', undefined)
              this.$set(lastItem, 'realQuantity', undefined)
              this.$set(lastItem, 'realSalePrice', undefined)
              this.$set(lastItem, 'eachUsageAmount', undefined)
              return 
            }
          }
          
          this.$set(lastItem, 'planQuantity', lastItem.planUsageDays * lastItem.eachUsageAmount)
          this.$set(lastItem, 'planUsageDaysInfoStart', 0)
          this.$set(lastItem, 'planUsageDaysInfoEnd', 0)
          this.$set(lastItem, 'planUsageDaysInfo', '')
          const planUsageDaysInfoEnd = this.getPlanDaysInfoEnd(row, groupItemList, patient)
          console.log('row.planUsageDaysInfoEnd', planUsageDaysInfoEnd)
          if(new Decimal(patient.visit.planUsageDays).comparedTo(new Decimal(planUsageDaysInfoEnd).plus(1)) >= 0) {
            this.$set(lastItem, 'planUsageDaysInfoStart', new Decimal(planUsageDaysInfoEnd).plus(1))
            this.$set(lastItem, 'planUsageDaysInfoEnd', lastItem.planUsageDaysInfoStart.plus(new Decimal(lastItem.planUsageDays).sub(1)))
            this.$set(lastItem, 'planUsageDaysInfo', lastItem.planUsageDaysInfoStart + '-' + lastItem.planUsageDaysInfoEnd + '天')
            if(Number(lastItem.planUsageDaysInfoStart) == Number(lastItem.planUsageDaysInfoEnd)) {
              this.$set(lastItem, 'planUsageDaysInfo', lastItem.planUsageDaysInfoStart + '天')
            }
          }
          // 计算最后一行片数与金额
          this.updatePrice(lastItem)
          this.verifyGroupDays(list, index, patient)
        }
      }
    },
    getPlanDaysInfoEnd(row, groupList, patient) {
      var planDaysInfoEnd = patient.visit.planUsageDays
      const index = groupList.indexOf(row)
      for (let i = index; i >= 0; i++) {
        const element = groupList[i];
        if(element.planUsageDaysInfoEnd) {
          planDaysInfoEnd = element.planUsageDaysInfoEnd
          break
        }
      }
      return planDaysInfoEnd
    },
    inputSubDrugPlanUsageDays(index, patient) {
      var list = patient.visitSubPackageDrugList
      var curRow = list[index]
      var curGroupList = this.getCurGroupList(index, list)
      if(!curRow.planUsageDays) this.$set(curRow, 'planUsageDays', 0)
      // 如果是分组
      if(curGroupList.length > 1) {
        // 如果是倒数第二个
        var lastItem = curGroupList[curGroupList.length - 1]
        if(curGroupList[curGroupList.length -2].serialNum == curRow.serialNum) {
          this.$set(lastItem, 'planUsageDays', 0)
          this.$set(lastItem, 'planUsageDaysInfoStart', undefined)
          this.$set(lastItem, 'planUsageDaysInfoEnd', undefined)
          this.$set(lastItem, 'planUsageDaysInfo', undefined)
        }
        var sumPlanUsageDaysInGroup = this.sumPlanUsageDaysInGroup(curGroupList)
        if (Number(sumPlanUsageDaysInGroup) > Number(patient.visit.planUsageDays)) {
          if(Number(lastItem.planUsageDays) != 0) {
            this.$set(lastItem, 'planUsageDays', lastItem.planUsageDays-1)
          } else {
            const rowPlanUsageDays = patient.visit.planUsageDays - (sumPlanUsageDaysInGroup - curRow.planUsageDays)
            this.$set(curRow, 'planUsageDays', rowPlanUsageDays)
            return
          }
        }
      } else {
        if(Number(curRow.planUsageDays) > Number(patient.visit.planUsageDays)) {
          this.$set(curRow, 'planUsageDays', patient.visit.planUsageDays)
          return
        }
      }
      this.$set(curRow, 'planUsageDays', Number(curRow.planUsageDays))
      if(curRow.planUsageDays < 0) curRow.planUsageDays = 0
      if(curRow.usagePurpose == '日常') {
        // this.updateLastDays(list, index, patient)
        // if(!this.verifyGroupDays(list, index, patient)) {
        //   this.$set(list[index], 'planUsageDays', 0)
        //   this.$message.error('处方天数有误')
        //   return
        // }
        var planUsageDaysInfoStart = new Decimal(1)
        var planUsageDaysInfoEnd
        // 如果是第一个，从第1天开始
        if(new Decimal(curRow.serialNum).isInteger()) {
          if(curRow.planUsageDays) {
            planUsageDaysInfoEnd = planUsageDaysInfoStart.plus(new Decimal(curRow.planUsageDays).sub(1))
          }
        } else {
          var preRow = list[index-1]
          planUsageDaysInfoStart =  new Decimal(preRow.planUsageDaysInfoEnd).plus(1)
          planUsageDaysInfoEnd = planUsageDaysInfoStart.plus(new Decimal(curRow.planUsageDays).sub(1))
        }
        this.$set(curRow, 'planUsageDaysInfoStart', planUsageDaysInfoStart)
        this.$set(curRow, 'planUsageDaysInfoEnd', planUsageDaysInfoEnd)
        this.$set(curRow, 'planUsageDaysInfo', curRow.planUsageDays <= 0 ? '' : curRow.planUsageDaysInfoStart + '-' + curRow.planUsageDaysInfoEnd + '天')
        if(Number(curRow.planUsageDaysInfoStart) == Number(curRow.planUsageDaysInfoEnd)) {
          this.$set(curRow, 'planUsageDaysInfo', curRow.planUsageDaysInfoStart + '天')
        }
        // 倒数第二个 在blur中计算最后一个的处方天数
        if(list[index+1] && !new Decimal(list[index+1].serialNum).isInteger()   // 下一个有值 且非整数
        && (!list[index+2] || list[index+2] && new Decimal(list[index+2].serialNum).isInteger())) { // 且 下下一个没有值或有值为整数
          var lastItem = curGroupList[curGroupList.length - 1]
          this.$set(lastItem, 'planUsageDays', 0)
          this.$set(lastItem, 'planUsageDaysInfoStart', undefined)
          this.$set(lastItem, 'planUsageDaysInfoEnd', undefined)
          this.$set(lastItem, 'planUsageDaysInfo', undefined)
          this.verifyGroupDays(list, index, patient)
        }
      } else {
        if(curRow.usagePurpose == '日常特') {
          // 计算到期天数
          if(curRow.planUsageStartDays) {
            const maxPlanUsageDays = patient.visit.planUsageDays - curRow.planUsageStartDays + 1
            if(curRow.planUsageDays >= maxPlanUsageDays) {
              this.$set(curRow, 'planUsageDays', maxPlanUsageDays)
            }
            curRow.planUsageDaysInfo = curRow.planUsageStartDays + '-' + new Decimal(curRow.planUsageStartDays).plus(curRow.planUsageDays).sub(1) + '天'
          }
        }
      }
      this.$set(curRow, 'realUsageDays', curRow.planUsageDays)
      // 计算片数与金额
      if(curRow.eachUsageAmount && curRow.unitPrice) {
        this.$set(curRow, 'planQuantity', curRow.planUsageDays * curRow.eachUsageAmount)
        this.$set(curRow, 'planSalePrice',  (curRow.planQuantity * curRow.unitPrice).toFixed(2))
        var reserveNum = curRow.reserveNum && curRow.planUsageDays != 0 ? curRow.reserveNum : 0
        this.$set(curRow, 'realUsageDays', curRow.planUsageDays)
        this.$set(curRow, 'realQuantity', curRow.realUsageDays * curRow.eachUsageAmount - reserveNum)
        this.$set(curRow, 'realSalePrice',  (curRow.realQuantity * curRow.unitPrice).toFixed(2))
      }
      this.updateSubPackageReports(patient)
    },
    // updateLastDays(list, index, patient) {
    //   var nextList = []
    //   if(nextList && nextList.length == 0) return
    //   nextList.shift()
    //   nextList.forEach(item=> {
    //     this.$set(item, 'planUsageDays', 0)
    //     item.planUsageDaysInfo = undefined
    //   })
    // },
    verifyGroupDays(list, index, patient) {
      var groupItemList = this.getCurGroupList(index, list)
      var sumDays = new Decimal(0)
      for (const element of groupItemList) {
        if(element.planUsageDays) {
          sumDays = sumDays.plus(new Decimal(element.planUsageDays))
          console.log('sumDays', sumDays)
          if(Number(sumDays) > Number(patient.visit.planUsageDays)) {
            this.$set(element, 'planUsageDays', 0)
            this.$message.error('输入天数有误')
            return false
          }
        }
      }
      if(groupItemList.filter(item => !item.planUsageDays || item.planUsageDays==0 ).length != 0) return true
      var sumDays = groupItemList.reduce((sum, obj) => sum + Number(obj.planUsageDays), 0);
      if(sumDays != patient.visit.planUsageDays) {
        return false
      }
      return true
    },
    sumPlanUsageDaysInGroup(groupList) {
      var sumDays = new Decimal(0)
      for (const element of groupList) {
        if(element.planUsageDays) {
          sumDays = sumDays.plus(new Decimal(element.planUsageDays))
        }
      }
      return sumDays
    },
    inputSubDrugPlanUsageStartDays(curRow, patient) {
      if(!curRow.planUsageStartDays) {
        curRow.planUsageDaysInfo = ''
        return 
      }
      if(curRow.planUsageDays) {
        this.$set(curRow, 'planUsageStartDays', curRow.planUsageStartDays > (patient.visit.planUsageDays - curRow.planUsageDays + 1) ? (patient.visit.planUsageDays - curRow.planUsageDays + 1) : curRow.planUsageStartDays)
        curRow.planUsageDaysInfo = curRow.planUsageStartDays + '-' + new Decimal(curRow.planUsageStartDays).plus(curRow.planUsageDays).sub(1) + '天'
      }
    },
    selectUsagePurpose(usagePurpose, subDrugScope, patient) {
      // 清空处方天数列信息
      this.$set(subDrugScope, 'planUsageDays', undefined)
      this.$set(subDrugScope, 'planUsageStartDays', undefined)
      this.$set(subDrugScope, 'planUsageDaysInfo', undefined)
      this.$set(subDrugScope, 'repairDate', undefined)
      this.$set(subDrugScope, 'repairDateStr', undefined)
      if(usagePurpose == '日常') {
        subDrugScope.planUsageDays = patient.visit.planUsageDays
        subDrugScope.realUsageDays = patient.visit.planUsageDays
        subDrugScope.isDisabledPlanUsageDays = true
      } else if(usagePurpose == '日常特') {
        subDrugScope.isDisabledPlanUsageDays = false
        this.initPlanQuantity(subDrugScope)
      } else if(usagePurpose == '备用') {
        subDrugScope.isDisabledPlanUsageDays = false
        this.initPlanQuantity(subDrugScope)
      } else if(usagePurpose == '补') {
        subDrugScope.planUsageDays = 0
        subDrugScope.isDisabledPlanUsageDays = true
        this.initPlanQuantity(subDrugScope)
      }
    },
    addGroup(index, patient) {
      var list = patient.visitSubPackageDrugList
      var curGroupList = this.getCurGroupList(index, list)
      var serialNum = new Decimal(curGroupList[curGroupList.length-1].serialNum).plus(0.1) 
      var item = {
        serialNum: serialNum,
        usagePurpose: '日常',
        code: '',
        commonName: '',
        isDisabledPlanUsageDays: false,
      }
      list[index].isGroup = true
      // // 最后一个
      // if(list.length == index+1) {
      //   list.splice(index+1, 0, item)
      //   return 
      // }
      var addIndex = this.getAddIndex(list, index+1)
      list[index].isDisabledPlanUsageDays = false
      item.isDisabledPlanUsageDays = false
      list.splice(addIndex, 0, item)
      // this.inputSubDrugPlanUsageDays(index, patient)
      curGroupList = this.getCurGroupList(index, list)
      for (const element of curGroupList) {
        element.isDisabledPlanUsageDays = false
      }
      curGroupList[curGroupList.length - 1].isDisabledPlanUsageDays = true
      
    },
    getAddIndex(list, index) {
      if(!list[index] || new Decimal(list[index].serialNum).isInteger()) {
        return index
      } else {
        return this.getAddIndex(list, index+1)
      }
    },
    inputReserveNum(row, patient) {
      console.log(row)
      if(row.reserveNum < 0) row.reserveNum = 0
      if(row.reserveNum > row.planQuantity) row.reserveNum = row.planQuantity
      this.$set(row, 'realQuantity',  row.planQuantity - row.reserveNum< 0 ? 0 : row.planQuantity - row.reserveNum)
      this.$set(row, 'realSalePrice',  (row.realQuantity * row.unitPrice).toFixed(2))
      this.updateSubPackageReports(patient)
    },
    inputPackageDrugQuantity(packageDrug, patient) {
      this.checkNumInput(packageDrug, 'realQuantity', packageDrug.realQuantity)
      if (packageDrug.realQuantity) {
        this.$set(packageDrug, 'realSalePrice', (packageDrug.realQuantity * packageDrug.unitPrice).toFixed(2))
      }

      var curReport = patient.visitPackageDrugRealReport[0]
      this.$set(curReport, 'guidanceCode', patient.guidanceCode)
      this.$set(curReport, 'realAmount', packageDrug.realSalePrice)
      this.$set(curReport, 'realCardAmount', packageDrug.realSalePrice)
      this.$set(curReport, 'realActivityAmount', packageDrug.realSalePrice)
      this.$set(curReport, 'realActivityCardAmount', packageDrug.realSalePrice)
    },
    inputEachForTime(packageDrug, patient) {
      this.checkNumInput(packageDrug, 'eachForTime', packageDrug.eachForTime)
    },
    checkNumInput(obj, prop, content) {
      // 判空
      if(!content) this.$set(obj, prop, 0)
      // 删除0开头
      this.$set(obj, prop, Number(content))
      // 负数时改为0
      if(!content) this.$set(obj, prop, 0)
    },
    async confirmVisit(patient, type) {
      if(type == 1) {

        this.$set(patient, 'visitActiveName', this.visitTitleEnum[type])
      } else if (type == 2) {
        // 实验室检查项提交
        for (const inspection of patient.visitInspectionList) {
          inspection.visitInspectionCard = patient.visitInspectionCard
        }
        var addInspectionReqDto = {
          guidanceCode: patient.guidanceCode,
          visitInspectionList: patient.visitInspectionList,
          visitInspectionRealReportList: patient.visitInspectionRealReport
        }
        console.log('addInspectionReqDto', addInspectionReqDto)
        addInspection(addInspectionReqDto).then(res=> {
          console.log(res)
          this.$set(patient, 'visitActiveName', this.visitTitleEnum[type])
        })
      }  else if (type == 3) {

        this.$set(patient, 'visitActiveName', this.visitTitleEnum[type])
      }  else if (type == 4) {

        this.$set(patient, 'visitActiveName', this.visitTitleEnum[type])
      }  else if (type == 5) {
        // 分装与整装药品 提交
        if(!this.checkVisit(patient)) return
        let visitDrugReq = {
          visitId: patient.visit.id, 
          guidanceCode: patient.guidanceCode,
          drugMark: patient.visit.drugMark,
          startUsageTime: patient.visit.startUsageTime,
          endUsageTime: patient.visit.endUsageTime,
          planUsageDays: patient.visit.planUsageDays,
          visitPackageCard: patient.visitPackageCard,
          visitSubPackageDrugList: patient.visitSubPackageDrugList,
          visitSubPackageDrugRealReport: patient.visitSubPackageDrugRealReport[0],
          visitPackageDrugList: patient.visitPackageDrugList,
          visitPackageDrugRealReport: patient.visitPackageDrugRealReport[0]
        }
        console.log('visitDrug req', visitDrugReq)
        const addVisitDrugRes = await addVisitDrug(visitDrugReq)
        console.log('addVisitDrugRes', addVisitDrugRes)
        this.$set(patient, 'visitActiveName', this.visitTitleEnum[type])

      } else if (type == 6) {
        var nextVisitReqDto = {
          guidanceCode: patient.guidanceCode,
          nextVisitDailyList: patient.nextVisitDailyList,
          nextVisitList: patient.nextVisitList,
          nextVisitRemark: patient.nextVisitRemark
        }
        console.log(nextVisitReqDto)
        addNextVisit(nextVisitReqDto).then(res=> {
          console.log("addNextVisit:", res)
          this.$set(patient, 'visitActiveName', undefined)
        })
      }
    },
    selectoperation(radioValue, inspection) {
      if(radioValue == 2) {
        this.$prompt('请输入不操作原因', '不操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S/,
          inputErrorMessage: '原因不能为空'
        }).then(({ value }) => {
          this.$set(inspection, 'operation', radioValue)
          this.$set(inspection, 'operationMark', value)
        }).catch((e) => {
          console.log(e)
        });
      } else {
        this.$set(inspection, 'operation', radioValue)
      }
      // source
      if(radioValue == 3) {
        if(inspection.source == '添加') this.$set(inspection, 'source', '预存')
        else inspection.source += '\n 预存'
      } else {
        inspection.source = inspection.source.split('\n').join('').split('预存').join('')
      }
    },
    inputRealQuantity(patient) {
      var reportObj = patient.visitInspectionRealReport[0]
      if(patient.visitInspectionList && patient.visitInspectionList.length != 0) {
        var sum = patient.visitInspectionList.reduce((sum, inspection) => sum + Number(Decimal(inspection.realQuantity).mul(Decimal(inspection.unitPrice))), 0)
        this.$set(reportObj, 'planAmount', Decimal(sum).toFixed(1, Decimal.ROUND_HALF_UP)) 
        if(patient.visitInspectionList && patient.visitInspectionList.length != 0) {
          patient.visitInspectionList.forEach(item => {
            this.$set(item, 'totalPrice1', item.realQuantity ? Decimal(item.realQuantity).mul(item.unitPrice) : 0)
            this.$set(item, 'totalPrice2', item.realQuantity ? Decimal(item.realQuantity).mul(item.unitPrice) : 0)
          })
        }
      }
    },
    delDrug(index, list, patient) {
      console.log('DEL drug LIST', list)
      const drug = list[index]
      console.log('del drug', drug)
      this.$confirm('删除 '+ drug.code + ' ' + drug.commonName +', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if(Number.isInteger(Number(drug.serialNum))) {
          // 删除组
          var curGroupList = this.getCurGroupList(index, list)
          list.splice(index, curGroupList.length)
          // 后面的序号都减1
          for (let i = index; i < list.length; i++) {
            const element = list[i];
            element.serialNum = new Decimal(element.serialNum).sub(1)
          }
        } else {
          // 删除分组的小数行
          list.splice(index, 1)
          // 组内序号减0.1
          for (let i = index; i < list.length; i++) {
            const element = list[i]
            if(!Number.isInteger(Number(element.serialNum))) {
              element.serialNum = new Decimal(element.serialNum).sub(0.1)
            } else {
              break
            }
          }
          // 因为当前删除的是小数， 所以index-1 一定还是在组内
          var curGroupList = this.getCurGroupList(index-1, list)
          if(curGroupList.length == 1) {
            this.$set(curGroupList[0], 'isGroup', false)
            this.$set(curGroupList[0], 'isDisabledPlanUsageDays', true)
            this.$set(curGroupList[0], 'planUsageDays', patient.visit.planUsageDays)
            this.$set(curGroupList[0], 'planUsageDaysInfo', '')
          } else {
            curGroupList[curGroupList.length - 1].isDisabledPlanUsageDays = true
          }
        }
        this.updateSubPackageReports(patient)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
    },
    getCurGroupList(index, list) {
      let curGroupList = []
      let curItem = list[index]
      for (let i = index; i >= 0; i--) {
        if(this.isSameGroup(list[i], curItem) == false) {
          break
        }
        curGroupList.unshift(list[i])
      }
      if(list[index+1]) {
        for (let i = index+1; i < list.length; i++) {
          const element = list[i];
          if(this.isSameGroup(element, curItem) == false) {
            break
          }
          curGroupList.push(element)
        }
      }
      return curGroupList
    },
    isSameGroup(item1, item2) {
      if((''+Number(item1.serialNum)).slice(0, 1) == (''+Number(item2.serialNum)).slice(0, 1)) {
        return true
      }
      return false
    },
    changeReserve(row, patient) {
      row.reserveNum = 0
      if(row.isReserve == false) {
        this.$set(row, 'realQuantity',  row.planQuantity - row.reserveNum< 0 ? 0 : row.planQuantity - row.reserveNum)
        this.$set(row, 'realSalePrice',  (row.realQuantity * row.unitPrice).toFixed(2))
        this.updateSubPackageReports(patient)
      }
    },
    changeRepairDate(row) {
      if(!row.repairDate) {
        this.$set(row, 'planUsageDays', undefined)
        this.$set(row, 'repairDateStart', undefined)
        this.$set(row, 'repairDateEnd', undefined)
        this.$set(row, 'planQuantity', undefined)
        this.$set(row, 'planSalePrice',  undefined)
        this.$set(row, 'realQuantity', undefined)
        this.$set(row, 'realSalePrice',  undefined)
        row.repairDateStr = undefined
        return
      }
      this.initPlanQuantity(row)
      const startDate = row.repairDate[0]
      const endDate = row.repairDate[1]
      const startDateStr = dateToString(startDate, 1).substr(2)
      const endDateStr = dateToString(endDate, 1).substr(2)
      row.repairDateStr = startDateStr + '-' + endDateStr
      // 相差天数
      this.$set(row, 'planUsageDays', betweenDate(startDate, endDate, 'day'))
      this.$set(row, 'repairDateStart', startDate)
      this.$set(row, 'repairDateEnd', endDate)
      if(row.eachUsageAmount) {
        this.$set(row, 'planQuantity', row.planUsageDays * row.eachUsageAmount)
        if(row.planQuantity && Number(row.planQuantity) > Number(row.num)) {
          row.planUsageDays = undefined
          row.repairDateStart = undefined
          row.repairDateEnd = undefined
          row.repairDateStr = undefined
          this.initPlanQuantity(row)
          this.$alert(row.code + '[' + row.commonName + ']' +'库存不足, 库存数量:[' + row.num + ']', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return
        }
        this.$set(row, 'planSalePrice',  (row.planQuantity * row.unitPrice).toFixed(2))
        var reserveNum = row.reserveNum && row.planUsageDays != 0 ? row.reserveNum : 0
        this.$set(row, 'realUsageDays', row.planUsageDays)
        this.$set(row, 'realQuantity', row.realUsageDays * row.eachUsageAmount - reserveNum)
        this.$set(row, 'realSalePrice',  (row.realQuantity * row.unitPrice).toFixed(2))
      }
    },
    initPlanQuantity(row) {
      this.$set(row, 'planQuantity', undefined)
      this.$set(row, 'planSalePrice',  undefined)
      this.$set(row, 'realQuantity', undefined)
      this.$set(row, 'realSalePrice',  undefined)
      this.$set(row, 'realUsageDays',  undefined)
      console.log('initPlanQuantity row', row)
    },
    checkVisit(patient) {
      if(!patient.visit.planUsageDays || patient.visit.planUsageDays == 0 || patient.visit.planUsageDays == '') {
        this.$alert('请填写处方天数', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return false
      } else if (!patient.visit.startUsageTime) {
        this.$alert('请选择开始发药日期', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return false
      }
      for (const item of patient.visitSubPackageDrugList) {
        if(!item.planUsageDays || item.planUsageDays == 0 || item.planUsageDays == '') {
          this.$alert('请填写 ' + item.code + '[' + item.commonName + '] 处方天数', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return false
        } else if (!item.eachUsageAmount || item.eachUsageAmount == 0 || item.eachUsageAmount == '') {
          this.$alert('请填写 ' + item.code + '[' + item.commonName + '] 片/次', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return false
        } else if (!item.usageMode || item.usageMode == '') {
          this.$alert('请填写 ' + item.code + '[' + item.commonName + '] 次/天', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return false
        } else if (!item.usagePurpose || item.usagePurpose == '') {
          this.$alert('请填写 ' + item.code + '[' + item.commonName + '] 用途', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return false
        } else if (!item.planQuantity || Number.isInteger(Number(item.planQuantity)) == false) {
          this.$alert(item.code + '[' + item.commonName + '] 处方片数出现小数', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return false
        }
        if(item.usagePurpose == '日常特') {
          if(!item.planUsageStartDays || item.planUsageStartDays == '') {
            this.$alert(item.code + '[' + item.commonName + '] 未填写开始天数', '错误', {
              confirmButtonText: '确定',
              type: 'error',
            });
            return false
          }
        }
      }
      return true
    },
    drugIsPaidClassName({row}) {
      if (row.status != 0) {
        return 'drug-row-paid';
      }
      return '';
    }
    
  }
}
</script>


<style lang="scss" scoped>
  .el-aside {
    width: 20%;
    text-align: center;
  }
  
  .el-main {
    width: 80%;
    text-align: left;
  }
  
  body > .el-container {
    margin-bottom: 20px;
  }
  .main-head-title {
    font-size: 14px;
  }
  .el-table .cell {
    white-space: pre-line;
  }

  .job-status {
    display: flex;
    justify-content: flex-start;
  }
  .job-status-item {
    width: 18%;
    padding: 10px;
    margin: 10px;
    border-radius: 10px;
    background-color: #f5f5f5;
  }
  
  .del-btn {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 4px;
  }

  
  ::v-deep .el-input-group__append {
    padding: 0 5px;
  }

  .first-row {
    position: absolute;
    top: 1px;
    left: 3px;
    width: 93%;
  }

  .second-row {
    position: absolute;
    top: 31px;
    left: 3px;
    width: 93%;
  }

  .third-row {
    position: absolute;
    top: 58px;
    width: 93%;
    padding-top: 0;
  }
  .third-row-select {
    position: absolute;
    left: 3px;
    top: 60px;
    width: 93%;
    padding-top: 0;
  }
  
  .repair-box ::v-deep .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 93%;
    margin: 0 0
  }

  ::v-deep .el-tabs__item {
    height: 30px;
    line-height: 30px;
  }
  .app-container > ::v-deep .el-tabs--border-card > .el-tabs__header{
    position: fixed;
    z-index: 98;
    top: 84px;
  }

  .el-main > .patient-base-info > .el-collapse {
    position: fixed;
    z-index: 98;
    top: 160px;
    width: 72%
  }
  .el-main > ::v-deep .el-tabs--border-card {
    margin-top: 70px;
  }
  .patient-base-info {
    position: fixed;
    z-index: 97;
    background-color: #fff;
    width: 72%;
    padding: 0 16px;
  }

//   ::v-deep .el-input__inner{
//     width: 80px;
//     height: 30px;
//  }
  ::v-deep .el-table .drug-row-paid {
    background-color: #f5f7fa;
  }

  
</style>